Find the extension of a filename in Ruby

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


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".

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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 - Ruby on-Rails

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 - Ruby on-Rails

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 - Ruby on-Rails

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

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

Solution 5 - Ruby on-Rails

This post answered my question, however my use case was the opposite. I wanted to find the name of the file without the extension. I found the file name with File.basename, then combined File.extname with gsub to remove the .md like so:

@file = '/path/to/my-file-name.md' 
File.basename(@file).gsub(File.extname(@file),'')

# => 'my-file-name'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBryan CosgroveView Question on Stackoverflow
Solution 1 - Ruby on-RailsFelixView Answer on Stackoverflow
Solution 2 - Ruby on-RailsmegasView Answer on Stackoverflow
Solution 3 - Ruby on-RailsgertasView Answer on Stackoverflow
Solution 4 - Ruby on-RailsNicoDevView Answer on Stackoverflow
Solution 5 - Ruby on-RailsDaveWoodall.comView Answer on Stackoverflow