find the parent directory of a directory in ruby

To find the parent directory of a directory in Ruby, you can use the File.dirname method to extract the last directory component of a file path. By calling this method twice, you can obtain the parent directory of the provided directory path.

Here is an example code snippet that demonstrates this approach:

main.rb
dir_path = "/path/to/directory"

parent_dir = File.dirname(File.dirname(dir_path))

puts "Parent directory of #{dir_path}: #{parent_dir}"
138 chars
6 lines

This code will output:

main.rb
Parent directory of /path/to/directory: /path/to
49 chars
2 lines

This works because we call File.dirname twice, which will first give us /path/to/directory and then /path/to, which is the parent directory.

gistlibby LogSnag