What is the File.extname() method in Ruby?

Overview

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.

Syntax

File.extname(file_name)

Parameters

file_name: This is the file whose extension name we get.

Return value

This method returns the extension of the file file_name.

Code example

Let’s consider an example to see this method in action.

# Create the file names
fn1 = "main.rb"
fn2 = "app.js"
fn3 = "main.java"
fn4 = "app.py"
# Get the extension names
puts File.extname(fn1)
puts File.extname(fn2)
puts File.extname(fn3)
puts File.extname(fn4)

Explanation

  • Lines 2 to 5: We create some file names with their respective extensions.
  • Lines 8 to 11: We use the File.extname() method to get the extension of each file. Then, we print these extensions to the console with the puts method.

Free Resources