Dexygen
Dexygen

Reputation: 12561

How to get the current working directory's absolute path in Ruby?

I'm running Ruby on Windows though I don't know if that should make a difference. All I want to do is get the current working directory's absolute path. Is this possible from irb? Apparently from a script it's possible using File.expand_path(__FILE__)

But from irb I tried the following and got a "Permission denied" error:

File.new(Dir.new(".").path).expand

Upvotes: 323

Views: 274474

Answers (7)

copremesis
copremesis

Reputation: 776

If you don't plan on running your code on Windows or anything other than *nix.

`pwd`.chop

Upvotes: 0

user85509
user85509

Reputation: 37682

Dir.pwd is the current working directory

http://ruby-doc.org/core/Dir.html#method-c-pwd

Upvotes: 589

udo
udo

Reputation: 1516

As for the path relative to the current executing script, since Ruby 2.0 you can also use

__dir__

So this is basically the same as

File.dirname(__FILE__)

Upvotes: 71

yeshwant singh
yeshwant singh

Reputation: 164

Through this you can get absolute path of any file located in any directory.

File.join(Dir.pwd,'some-dir','some-file-name')

This will return

=> "/User/abc/xyz/some-dir/some-file-name"

Upvotes: 6

Châu Hồng Lĩnh
Châu Hồng Lĩnh

Reputation: 1823

If you want to get the full path of the directory of the current rb file:

File.expand_path('../', __FILE__)

Upvotes: 5

This will give you the working directory of the current file.

File.dirname(__FILE__)

Example:

current_file: "/Users/nemrow/SITM/folder1/folder2/amazon.rb"

result: "/Users/nemrow/SITM/folder1/folder2"

Upvotes: 6

Psylone
Psylone

Reputation: 2808

File.expand_path File.dirname(__FILE__) will return the directory relative to the file this command is called from.

But Dir.pwd returns the working directory (results identical to executing pwd in your terminal)

Upvotes: 199

Related Questions