291
votes

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
6
The question is not actually clear: Do you want a) the current working directory (which is Dir.pwd) or do you want the directory where the currently running script is located (which is File.dirname(__FILE__))? Imagine calling a script from anywhere else (like ruby testdirectory/testscript.rb) here, the two will be different! - amenthes
@amenthes You claim my question is unclear and then ask "Do you want a) the current working directory ...." and my question states "All I want to do is get the current working directory's absolute path...". What's unclear? - Dexygen
it's unclear because of the sentence " Apparently from a script it's possible using File.expand_path(__FILE__)" - because __FILE__'s location is a different animal than current working dir (which is Dir.pwd). - amenthes
@amenthes I thought I did a pretty good job differentiating "from irb" which is right there in the title of the question (and twice within the question itself), from "from a script" - Dexygen
The reason the question is very unclear is that even in a script, File.expand_path(__FILE__) does not "get the current working directory's absolute path". - Ken Williams

6 Answers

190
votes

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)

63
votes

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__)
6
votes

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"

6
votes

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"
5
votes

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

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