91

Inspired by "Getting the source directory of a Bash script from within", what's the Ruby way to do this?

Community
  • 1
  • 1
java.is.for.desktop
  • 10,748
  • 12
  • 69
  • 103

4 Answers4

127

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; or
  • File.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.

Itay Grudev
  • 7,055
  • 4
  • 54
  • 86
gaqzi
  • 3,707
  • 3
  • 30
  • 30
88

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?".

Nathan Long
  • 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
11

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
reducing activity
  • 1,985
  • 2
  • 36
  • 64
-10

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

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
Shadowfirebird
  • 757
  • 3
  • 13