65

I understand I can get current directory by

$CurrentDir = Dir.pwd

How about parent directory of current directory?

Zack Zatkin-Gold
  • 784
  • 8
  • 29
icn
  • 16,048
  • 37
  • 102
  • 135

4 Answers4

128
File.expand_path("..", Dir.pwd)
August
  • 11,094
  • 3
  • 32
  • 48
Rob Di Marco
  • 40,674
  • 8
  • 65
  • 56
16

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"
Keith Bennett
  • 4,562
  • 1
  • 22
  • 34
16

Perhaps the simplest solution:

puts File.expand_path('../.') 
Marek Příhoda
  • 10,868
  • 3
  • 37
  • 52
4

In modern Ruby you should definitely use Pathname.

Pathname.getwd.parent
akim
  • 7,642
  • 2
  • 41
  • 56
  • That's pretty neat. You'd probably almost always need to call `.to_s` on that to convert it to a String (it's a Pathname). – Keith Bennett Sep 14 '21 at 21:41
  • 1
    In my experience you rarely need `to_s`, but rather you should embrace Pathname everywhere for file names, rather than String. – akim Sep 15 '21 at 14:45