What is File.basename() in Ruby?

Overview

We use the **`basename()` method** of the `File` instance to return the file name of the specified `file_name`. If a `suffix` is given and it is present at the end of the file name, then the `suffix` is removed.

Syntax

```ruby File.basename(file_name, suffix) ```

Parameters

**`file_name`**: This is the file name of the file.

suffix: This is the file extension. If the suffix is present, then the file name will be returned with its suffix removed.

Return value

This method returns a file name.

Code example

main.rb
test.py
test.js
test.txt
# create some file names
fn1 = "main.rb"
fn2 = "test.js"
fn3 = "test.txt"
fn4 = "test.py"
# use the basename() without suffix
puts File.basename(fn1) # main.rb
puts File.basename(fn2) # test.js
# use the basename() with suffix
puts File.basename(fn3, ".txt") # test
puts File.basename(fn4, ".py") # test

Code explanation

* We create the files `main.rb`, `test.txt`, `test.js`, and `test.py`. * We find our application code in the `main.rb` file. * **Lines 2–5**: We create four variables with the file names we need. * **Lines 8–9**: We take the base names of the files, using the `basename()` method and without passing the `suffix` argument. Then, we print the results to the console. * **Lines 12–13**: We also use the `basename()` method to get the base names of the files and we pass their suffixes as arguments. After that, we print the results to the console.

Free Resources