Find the extension of a filename in Ruby

I'm working on the file upload portion of a Rails app. Different types of files are handled differently by the app.

I want to make a whitelist of certain file extensions to check the uploaded files against to see where they should go. All of the file names are strings.

I need a way to check only the extension part of the file name string. The file names are all in the format of "some_file_name.some_extension".


Solution 1:

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

Solution 2:

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"

Solution 3:

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"

Solution 4:

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

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