Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 923
java.is.for.desktop Avatar asked Feb 05 '10 11:02

java.is.for.desktop


People also ask

How do I find the path of a file in Ruby?

Pass a string to File. expand_path to generate the path to that file or directory. Relative paths will reference your current working directory, and paths prepended with ~ will use the owner's home directory.

What is directory in Ruby?

A directory is a location where files can be stored. For Ruby, the Dir class and the FileUtils module manages directories and the File class handles the files.

How do I change directory in Ruby?

chdir : To change the current working directory, chdir method is used. In this method, you can simply pass the path to the directory where you want to move. The string parameter used in the chdir method is the absolute or relative path.

What is __ file __ in Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.


2 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; 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.

like image 84
gaqzi Avatar answered Oct 03 '22 03:10

gaqzi


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

like image 21
Nathan Long Avatar answered Oct 03 '22 04:10

Nathan Long