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
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 namesfn1 = "main.rb"fn2 = "test.js"fn3 = "test.txt"fn4 = "test.py"# use the basename() without suffixputs File.basename(fn1) # main.rbputs File.basename(fn2) # test.js# use the basename() with suffixputs File.basename(fn3, ".txt") # testputs File.basename(fn4, ".py") # test
Code explanation
- We create the files
main.rb,test.txt,test.js, andtest.py. - We find our application code in the
main.rbfile. - 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 thesuffixargument. 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.