I have a Ruby script which wants to determine its absolute path in order to find some data files that are stored relative to the script.
What's the simplest/best 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.
pwd : To check the current working directory, pwd(present working directory) method is used. 5. chdir : To change the current working directory, chdir method is used.
permalink #__dir__ ⇒ StringReturns the canonicalized absolute path of the directory of the file from which this method is called. It means symlinks in the path is resolved. If __FILE__ is nil , it returns nil . The return value equals to File.
Ruby has a method for this case. It is File::expand_path . Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point.
This can be done simply using:
File.expand_path $0
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