Get parent directory of current directory in Ruby

39,462

Solution 1

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

Solution 2

Perhaps the simplest solution:

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

Solution 3

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

In modern Ruby you should definitely use Pathname.

Pathname.getwd.parent
Share:
39,462
Kyaw Siesein
Author by

Kyaw Siesein

Software Engineer, rails, ruby, django,web2py,puppet, python,linux

Updated on July 08, 2022

Comments

  • Kyaw Siesein
    Kyaw Siesein almost 2 years

    I understand I can get current directory by

    $CurrentDir = Dir.pwd
    

    How about parent directory of current directory?

  • mu is too short
    mu is too short over 12 years
    @Niklas: Or File.expand_path('..'), the default dir_string is '.'.
  • mu is too short
    mu is too short over 12 years
    Why not just File.expand_path('..')?
  • Niklas B.
    Niklas B. over 12 years
    @muistooshort: nice to know :)
  • Marek Příhoda
    Marek Příhoda over 12 years
    @muistooshort indeed interesting, and definitly useful to know, thanks ;)
  • mu is too short
    mu is too short over 12 years
    Your answer piqued my curiosity to check the spec for File.expand_path so thanks for that.
  • Som Poddar
    Som Poddar about 9 years
    The solution suggested above did not work for me using ruby 2.1.5. The following did ... File.dirname(File.expand_path('..', __FILE__))
  • Keith Bennett
    Keith Bennett almost 3 years
    My answer here works, but is not as expressive and clear as the other answers.
  • Keith Bennett
    Keith Bennett almost 3 years
    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).
  • akim
    akim almost 3 years
    In my experience you rarely need to_s, but rather you should embrace Pathname everywhere for file names, rather than String.