Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

directory

ruby

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?

like image 852
Orcris Avatar asked Jun 17 '12 19:06

Orcris


People also ask

What is Dir in Ruby?

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.

What does __ file __ mean in Ruby?

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.

How do I change the working directory in Ruby?

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.


2 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.

like image 193
Fahim Parkar Avatar answered Sep 23 '22 00:09

Fahim Parkar


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.

like image 34
Santhosh Avatar answered Sep 23 '22 00:09

Santhosh