70

I understand I can get current directory by

$CurrentDir = Dir.pwd

How about parent directory of current directory?

Zack Zatkin-Gold
  • 814
  • 9
  • 29
icn
  • 17,126
  • 39
  • 105
  • 141

4 Answers4

133
File.expand_path("..", Dir.pwd)
August
  • 12,410
  • 3
  • 35
  • 51
Rob Di Marco
  • 43,054
  • 9
  • 66
  • 56
  • 15
    @Niklas: Or `File.expand_path('..')`, the [default `dir_string`](http://ruby-doc.org/core-1.9.3/File.html#method-c-expand_path) is `'.'`. – mu is too short Dec 28 '11 at 22:07
  • 6
    The solution suggested above did not work for me using `ruby 2.1.5`. The following did ... `File.dirname(File.expand_path('..', __FILE__))` – Som Poddar May 10 '15 at 23:23
17

Perhaps the simplest solution:

puts File.expand_path('../.') 
Marek Příhoda
  • 11,108
  • 3
  • 39
  • 53
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,722
  • 1
  • 25
  • 35
4

In modern Ruby you should definitely use Pathname.

Pathname.getwd.parent
akim
  • 8,255
  • 3
  • 44
  • 60
  • 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