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?
Advertisements. A Dir is a class to represent a directory stream that gives filenames in the directory in the operating system. Dir class also holds directory related operations, such as wild card filename matching, changing current working directory, etc. as class methods.
The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.
chdir : To change the current working directory, chdir method is used. In this method, you can simply pass the path to the directory where you want to move. The string parameter used in the chdir method is the absolute or relative path.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With