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,


Use method File.extname as follows,


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

=> ".jpg"
=> ""
# as there is no extension in the string passed as filename
# 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.


  • 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 Mohite

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

Read More
Buy me a coffee