Can a Ruby script tell what directory it’s in?

RubyScriptingPathDirectoryEnvironment Variables

Ruby Problem Overview


Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

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

Solution 3 - Ruby

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

Solution 4 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjava.is.for.desktopView Question on Stackoverflow
Solution 1 - RubygaqziView Answer on Stackoverflow
Solution 2 - RubyNathan LongView Answer on Stackoverflow
Solution 3 - Rubyreducing activityView Answer on Stackoverflow
Solution 4 - RubyShadowfirebirdView Answer on Stackoverflow