Find the extension of a filename in Ruby
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
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"
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"