find the name of a file in ruby

To find the name of a file in ruby, you can use the File.basename method. This method returns the last component of the filename given in path, which is separated by a separator File::SEPARATOR (or File::ALT_SEPARATOR).

main.rb
file_path = "/path/to/file.txt"
file_name = File.basename(file_path) # "file.txt"
82 chars
3 lines

You can also use File.basename with a second argument to specify a suffix that will be removed from the filename:

main.rb
file_path = "/path/to/file.txt"
file_name = File.basename(file_path, ".txt") # "file"
86 chars
3 lines

Note: If you only want to extract the directory path from a file path, use File.dirname instead of File.basename. It returns all the components of the path except the last one:

main.rb
file_path = "/path/to/file.txt"
dir_path = File.dirname(file_path) # "/path/to"
80 chars
3 lines

If you want to extract both the directory and the filename from a file path, you can use the File.split method:

main.rb
file_path = "/path/to/file.txt"
dir_path, file_name = File.split(file_path) # ["/path/to", "file.txt"]
103 chars
3 lines

gistlibby LogSnag