Get parent directory of current directory in Ruby

后端 未结 3 889
旧时难觅i
旧时难觅i 2020-12-13 03:33

I understand I can get current directory by

$CurrentDir = Dir.pwd

How about parent directory of current directory?

相关标签:
3条回答
  • 2020-12-13 03:58

    Perhaps the simplest solution:

    puts File.expand_path('../.') 
    
    0 讨论(0)
  • 2020-12-13 04:00

    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"
    
    0 讨论(0)
  • 2020-12-13 04:24
    File.expand_path("..", Dir.pwd)
    
    0 讨论(0)
提交回复
热议问题