Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the extension of a filename in Ruby

People also ask

How do I get the file extension in Ruby?

As there are more than one way of getting things done in Ruby, File extension also can be obtained in more than one way. Use of File#extname is more suitable in Ruby get file extension from string.

What is the extension of Ruby file?

An RB file is a software program written in Ruby, an object-oriented scripting language. Ruby is designed to be simple, efficient, and easy to read. RB files can be edited with a text editor and run using Ruby.

What is __ file __ in Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.


That's really basic stuff:

irb(main):002:0> accepted_formats = [".txt", ".pdf"]
=> [".txt", ".pdf"]
irb(main):003:0> File.extname("example.pdf") # get the extension
=> ".pdf"
irb(main):004:0> accepted_formats.include? File.extname("example.pdf")
=> true
irb(main):005:0> accepted_formats.include? File.extname("example.txt")
=> true
irb(main):006:0> accepted_formats.include? File.extname("example.png")
=> false

Use extname method from File class

File.extname("test.rb")         #=> ".rb"

Also you may need basename method

File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"

Quite old topic but here is the way to get rid of extension separator dot and possible trailing spaces:

File.extname(path).strip.downcase[1..-1]

Examples:

File.extname(".test").strip.downcase[1..-1]       # => nil
File.extname(".test.").strip.downcase[1..-1]      # => nil
File.extname(".test.pdf").strip.downcase[1..-1]   # => "pdf"
File.extname(".test.pdf ").strip.downcase[1..-1]  # => "pdf"

I my opinion it would be easier to do this to get rid of the extension separator.

File.extname(path).delete('.')