获取Ruby中当前目录的父目录

时间:2022-06-23 07:08:55

I understand I can get current directory by

我知道我可以通过当前目录

$CurrentDir = Dir.pwd

How about parent directory of current directory?

那么当前目录的父目录呢?

3 个解决方案

#1


94  

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

#2


12  

Perhaps the simplest solution:

也许最简单的解决方案:

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

#3


6  

I think an even simpler solution is to use File.dirname:

我认为更简单的解决方案是使用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.

文件。basename返回文件路径的组件。目录名不存在。

This, of course, works only if the filespec is absolute and not relative. To be sure to make it absolute one could do this:

当然,这只有在filespec是绝对而非相对的情况下才有效。要确保这是绝对可以做到的:

2.3.0 :008 > File.expand_path('.')
 => "/Users/kbennett/temp"
2.3.0 :009 > File.dirname(File.expand_path('.'))
 => "/Users/kbennett"

#1


94  

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

#2


12  

Perhaps the simplest solution:

也许最简单的解决方案:

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

#3


6  

I think an even simpler solution is to use File.dirname:

我认为更简单的解决方案是使用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.

文件。basename返回文件路径的组件。目录名不存在。

This, of course, works only if the filespec is absolute and not relative. To be sure to make it absolute one could do this:

当然,这只有在filespec是绝对而非相对的情况下才有效。要确保这是绝对可以做到的:

2.3.0 :008 > File.expand_path('.')
 => "/Users/kbennett/temp"
2.3.0 :009 > File.dirname(File.expand_path('.'))
 => "/Users/kbennett"