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.
File.basename(file_name, suffix)
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.
This method returns a file name.
# 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
main.rb
, test.txt
, test.js
, and test.py
.main.rb
file.basename()
method and without passing the suffix
argument. Then, we print the results to the console.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.