71

I understand I can get current directory by

$CurrentDir = Dir.pwd

How about parent directory of current directory?

4 Answers 4

134
File.expand_path("..", Dir.pwd)
2
  • 15
    @Niklas: Or File.expand_path('..'), the default dir_string is '.'. Commented Dec 28, 2011 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
    Commented May 10, 2015 at 23:23
17

Perhaps the simplest solution:

puts File.expand_path('../.') 
3
  • 11
    Why not just File.expand_path('..')? Commented Dec 28, 2011 at 22:07
  • @muistooshort indeed interesting, and definitly useful to know, thanks ;) Commented Dec 29, 2011 at 8:43
  • Your answer piqued my curiosity to check the spec for File.expand_path so thanks for that. Commented Dec 29, 2011 at 9:29
17

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"
1
  • My answer here works, but is not as expressive and clear as the other answers. Commented Sep 14, 2021 at 21:39
6

In modern Ruby you should definitely use Pathname.

Pathname.getwd.parent
2
  • 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). Commented Sep 14, 2021 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
    Commented Sep 15, 2021 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.