Get parent directory of current directory in Ruby

RubyDirectory

Ruby Problem Overview


I understand I can get current directory by

$CurrentDir = Dir.pwd

How about parent directory of current directory?

Ruby Solutions


Solution 1 - Ruby

File.expand_path("..", Dir.pwd)

Solution 2 - Ruby

Perhaps the simplest solution:

puts File.expand_path('../.') 

Solution 3 - Ruby

I think an even simpler solution is to use File.dirname:

2.3.0 :005 > Dir.pwd
 => "/Users/kbennett/temp"
2.3.0 :006 > File.dirname(Dir.pwd)
 => "/Users/kbennett"
2.3.0 :007 > File.basename(Dir.pwd)
 => "temp"

File.basename returns the component of the path that File.dirname does not.

This, of course, works only if the filespec is absolute and not relative. To be sure to make it absolute one could do this:

2.3.0 :008 > File.expand_path('.')
 => "/Users/kbennett/temp"
2.3.0 :009 > File.dirname(File.expand_path('.'))
 => "/Users/kbennett"

Solution 4 - Ruby

In modern Ruby you should definitely use Pathname.

Pathname.getwd.parent

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionicnView Question on Stackoverflow
Solution 1 - RubyRob Di MarcoView Answer on Stackoverflow
Solution 2 - RubyMarek PříhodaView Answer on Stackoverflow
Solution 3 - RubyKeith BennettView Answer on Stackoverflow
Solution 4 - RubyakimView Answer on Stackoverflow