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?
3 Answers
dirname = File.basename(Dir.getwd)
File.basename()
returns the base name even when its argument is the path of a directory.
To get absolute path, Dir.pwd seems to do the trick.
-
This actually returns name of folder from which is script run. Eg. If I am in
/my/folderx
and run./test/runme.eb
(which containsdirname = File.basename(Dir.getwd)
) thandirname => 'folderx'
nottest
– FotonApr 13, 2021 at 7:36
In Ruby 2.0 or greater, you can use Kernel#__dir__
:
__dir__
From the docs:
Returns the canonicalized absolute path of the directory of the file from which this method is called.
-
As mentioned in the question - "that only returns . and I want the actual name" (it is true also for ruby >=2.0.0, for example Ruby 2.3.3). Mar 22, 2017 at 15:25
File.expand_path(File.dirname(File.dirname(__FILE__)))
-
7
-
I believe this is a typo, however, it will work both ways: with the extra call to dirname and without:
File.expand_path(File.dirname(__FILE__))
– jaydelOct 23, 2019 at 14:00 -
The path of the script itself and the current working directory may be different. This is for the path of the script itself, not the current directory as far as I know.– MigMay 23, 2022 at 14:13