find the parent directory of a file in ruby

To find the parent directory of a file in Ruby, you can use the File.dirname method. This method takes the file path as an argument and returns the parent directory of that file.

main.rb
file_path = "/path/to/file.txt"
parent_dir = File.dirname(file_path)
puts parent_dir
85 chars
4 lines

Output:

main.rb
/path/to
9 chars
2 lines

In the example above, we first define the file path as a string. Then, we call the File.dirname method and pass in the file path as an argument. The return value of this method is the parent directory of the file, which we store in the parent_dir variable. Finally, we print the parent directory to the console.

Note that the above code assumes that the file path is a string. If you have a File object, you can get its path by calling the path method on it:

main.rb
file = File.new("/path/to/file.txt")
parent_dir = File.dirname(file.path)
puts parent_dir
90 chars
4 lines

Output:

main.rb
/path/to
9 chars
2 lines

gistlibby LogSnag