Get parent directory of current directory in Ruby

I understand that I can get the current directory

$CurrentDir = Dir.pwd 

What about the parent directory of the current directory?

+49
ruby directory
Dec 28 '11 at 8:10 a.m.
source share
3 answers
 File.expand_path("..", Dir.pwd) 
+90
Dec 28 '11 at 8:14 a.m.
source share
— -

Perhaps the simplest solution:

 puts File.expand_path('../.') 
+11
Dec 28 '11 at 20:43
source share

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 a component of the path that File.dirname does not support.

This, of course, only works if filepec is absolute and not relative. To make it absolute, you can do this:

 2.3.0 :008 > File.expand_path('.') => "/Users/kbennett/temp" 2.3.0 :009 > File.dirname(File.expand_path('.')) => "/Users/kbennett" 
+4
May 23 '16 at 2:51
source share



All Articles