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__),但它只返回。我想要真实的名字。我该怎么做呢?
3 个解决方案
#1
32
dirname = File.basename(Dir.getwd)
File.basename()
returns the base name even when its argument is the path of a directory.
basename()返回基名,即使其参数是目录的路径。
To get absolute path, Dir.pwd seems to do the trick.
为了得到绝对路径,Dir。pwd似乎做到了这一点。
#2
20
In Ruby 2.0 or greater, you can use Kernel#__dir__
:
在Ruby 2.0或更高版本中,您可以使用内核#__dir__:
__dir__
From the docs:
从文档:
Returns the canonicalized absolute path of the directory of the file from which this method is called.
返回调用此方法的文件的目录的规范化的绝对路径。
#3
8
File.expand_path(File.dirname(File.dirname(__FILE__)))
#1
32
dirname = File.basename(Dir.getwd)
File.basename()
returns the base name even when its argument is the path of a directory.
basename()返回基名,即使其参数是目录的路径。
To get absolute path, Dir.pwd seems to do the trick.
为了得到绝对路径,Dir。pwd似乎做到了这一点。
#2
20
In Ruby 2.0 or greater, you can use Kernel#__dir__
:
在Ruby 2.0或更高版本中,您可以使用内核#__dir__:
__dir__
From the docs:
从文档:
Returns the canonicalized absolute path of the directory of the file from which this method is called.
返回调用此方法的文件的目录的规范化的绝对路径。
#3
8
File.expand_path(File.dirname(File.dirname(__FILE__)))