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,
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,
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.
What not to do
Sometimes, idea may come to mind to extract filename from the string yourself using split method as follows,
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.