ruby 在Ruby中获取当前目录的父目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8660732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get parent directory of current directory in Ruby
提问by icn
I understand I can get current directory by
我知道我可以通过以下方式获取当前目录
$CurrentDir = Dir.pwd
How about parent directory of current directory?
当前目录的父目录如何?
回答by Rob Di Marco
File.expand_path("..", Dir.pwd)
回答by Marek P?íhoda
Perhaps the simplest solution:
也许最简单的解决方案:
puts File.expand_path('../.')
回答by Keith Bennett
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.basenamereturns the component of the path that File.dirnamedoes not.
File.basename返回路径File.dirname中没有的部分。
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"

