如何在 Ruby 中获取当前目录的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11074024/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:13:00  来源:igfitidea点击:

How do I get the name of the current directory in Ruby?

rubydirectory

提问by Orcris

How do I get the name of the current directory in Ruby? All I've found is File.dirname(__FILE__), but that only returns .and I want the actual name. How do I do this?

如何在 Ruby 中获取当前目录的名称?我发现的只是File.dirname(__FILE__),但这只会返回.并且我想要实际名称。我该怎么做呢?

回答by Fahim Parkar

dirname = File.basename(Dir.getwd)

File.basename()returns the base name even when its argument is the path of a directory.

File.basename()即使它的参数是目录的路径,也返回基本名称。

To get absolute path, Dir.pwdseems to do the trick.

为了获得绝对路径Dir.pwd似乎可以解决问题。

回答by Santhosh

In Ruby 2.0 or greater, you can use Kernel#__dir__:

在 Ruby 2.0 或更高版本中,您可以使用Kernel#__dir__

__dir__

From the docs:

从文档:

Returns the canonicalized absolute path of the directory of the file from which this method is called.

返回调用此方法的文件目录的规范化绝对路径。

回答by ennuikiller

File.expand_path(File.dirname(File.dirname(__FILE__)))