The File.extname()
or extname()
function of the File class in Ruby gets the extension of a file. For example, this function will return the extension of a Ruby application file main.rb
as .rb
.
File.extname(file_name)
file_name
: This is the file whose extension name we get.
This method returns the extension of the file file_name
.
Let’s consider an example to see this method in action.
# Create the file namesfn1 = "main.rb"fn2 = "app.js"fn3 = "main.java"fn4 = "app.py"# Get the extension namesputs File.extname(fn1)puts File.extname(fn2)puts File.extname(fn3)puts File.extname(fn4)
File.extname()
method to get the extension of each file. Then, we print these extensions to the console with the puts
method.