Inspired by "Getting the source directory of a Bash script from within", what's the Ruby way to do this?
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.
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.
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.
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.
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.
__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?".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With