How to Use the Ruby extname Method

09/25/2021

Contents

In this article, you will learn how to use the Ruby extname method.

Using the extname method

The Ruby extname method is used to extract the extension of a file name. It returns the extension, including the period (.), of a file name as a string. Here’s how to use the extname method in Ruby:

Call the extname method on a file name string:

filename = "example.txt"
extension = File.extname(filename)

The extname method will return the extension of the file name as a string:

puts extension # => ".txt"

If the file name does not have an extension, the extname method will return an empty string:

filename = "example"
extension = File.extname(filename)
puts extension # => ""

If the file name has multiple extensions, the extname method will return the last extension:

filename = "example.tar.gz"
extension = File.extname(filename)
puts extension # => ".gz"

The extname method can also be used with file paths:

filepath = "/home/user/example.txt"
extension = File.extname(filepath)
puts extension # => ".txt"

The extname method is case-sensitive and will return the extension as it appears in the file name or path:

filename = "example.TXT"
extension = File.extname(filename)
puts extension # => ".TXT"

It’s important to note that the extname method only returns the extension of a file name or path and does not validate whether the file actually exists or not:

filename = "nonexistent_file.txt"
extension = File.extname(filename)
puts extension # => ".txt"