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.
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.
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('.')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With