Inspired by "Getting the source directory of a Bash script from within", what's the Ruby way to do this?
4 Answers
For newer versions of Ruby, try:
__dir__
For older versions of Ruby (< 2.0), the script being run can be found using:
File.dirname(__FILE__)
- relative path; orFile.expand_path(File.dirname(__FILE__))
- the absolute path.
Note: Using __dir__
will return the script path even after a call to Dir.chdir
; whereas, using the older syntax may not return the path to the script.

- 7,055
- 4
- 54
- 86

- 3,707
- 3
- 30
- 30
-
The 'File.expand_path(File.dirname(__FILE__))' was useful in finding trhe absolute path – Kapidis Aug 19 '20 at 18:15
Use __dir__
As of Ruby 2.0, __dir__
is the simplest way to get this. It
Returns the canonicalized absolute path of the directory of the file from which this method is called.
See the __dir__
documentation, and "Why is __FILE__ uppercase and __dir__ lowercase?".

- 122,748
- 97
- 336
- 451
-
Well, aside from `__dir__` being the correct answer, thanks for also linking to the uppercase-vs-lowercase difference, was my first question after finding it as well :) – SidOfc Feb 06 '18 at 10:04
use __dir__
File.dirname(__FILE__)
is not a proper way to get directory where script is stored.
At start working directory and directory with script file is the same, but it may change.
For example:
Dir.chdir('..') do
puts __dir__
puts File.expand_path(File.dirname(__FILE__))
end
for script file stored in /Desktop/tmp
running it will give output
/home/mateusz/Desktop/tmp
/home/mateusz/Desktop

- 1,985
- 2
- 36
- 64
ENV["PWD"] seems the simplest way for me under Linux. I don't know of an OS-agnostic way.

- 278,309
- 50
- 514
- 539

- 757
- 3
- 13
-
-
That's the home directory, not the current working directory or the directory where the script is located. – Matthew Flaschen Feb 05 '10 at 11:21
-
B*gger, lack of sleep will do that. I meant ENV["PWD"] of course. But ba's answer is way better. – Shadowfirebird Feb 05 '10 at 11:24
-
15Isn't that simply the working directory of the process? I thought that the OP wanted the directory containing the script. – D.Shawley Feb 05 '10 at 12:23
-
No, the process could execute an external script from elsewhere. – java.is.for.desktop Feb 05 '10 at 12:40
-
This env var depends on the shell. It's nowhere near "reliable". E.g., services forked off `systemd` doesn't contain this variable at all. – iBug Mar 13 '22 at 12:09