Open In App

How to get filename without extension in Ruby?

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to get a filename in Ruby without its extension.

We can use the File.basename method to extract the last name of a filename. In Ruby, the File.basename method returns the last component of the filename.


Syntax:

File.basename(file_path [,suffix])

If we don’t provide any suffixes in the File.basename then it will only give the filename in the output as shown in the below example.

Example:

Ruby
filename = "home/anki/my_data/hello.rb"
filename_without_path = File.basename(filename)
puts filename_without_path

Output
hello.rb

To get the filename without extension, we have to provide a suffix .* in the File.basename. If suffix is .* , it removes any extension. Below is an example showing the use of .* :

Example:

Ruby
filename = "home/anki/my_data/hello.rb"
filename_without_extension = File.basename(filename, ".*")
puts filename_without_extension

Output
hello

Another example on how to get filename without extension:

Example:

Ruby
filename = "home/anki/my_data/hello.rb"
filename_without_extension = File.basename(filename, ".rb") 
puts filename_without_extension

Output
hello

In above example, we use .rb as suffix to remove the extension from the filename. This is another way to remove the extension from the filename. To use this, just provide .extension in the File.basename method.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads