/ RAILS

Ruby get file extension from string

Sometimes developer requires to extract only file extension from the string object. File class can be used to perform this operation. We will see how to use File class to get the extension name.

Let’s create a sample string with Filename  Suppose we have a file with name ruby-in-rails-logo.jpg and string object as,

filename = "ruby-in-rails-logo.jpg"

of which extension .jpg we want for some check in the program. Then we can use File class as follows,

Solution

Use method File.extname as follows,

Syntax:

file_extension = File.extname(filename)
=> ".jpg"

Method File#extname when passed string with filename then it returns extension of that file. In above example it is .jpg

You can read source page of File#extname on APIDock for the C source code of this method.

Sample Conversions

File.extname("ruby/in/rails/logo.jpg")
=> ".jpg"
File.extname("ruby-in-rails-logo")
=> ""
# as there is no extension in the string passed as filename
File.extname(".ruby-in-rails-logo")
""
# As not valid extension length, refer APIDock source for more on this.

What not to do

Sometimes, idea may come to mind to extract filename from the string yourself using split method as follows,

filename = "ruby-in-rails-logo.jpg"
extension = filename.split(".").last
=> "jpg"

Which will return result as “jpg” for you which is also the required result for your program. But the C level implementation for the File#extname is more suitable considering performance. Thus, using File#extname is advised.

Conclusion

  • 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.
akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee