I'm trying to get a reference to the script passed to the ruby interpreter. For example, if I'm running ruby foo.rb
I want to get a reference to the foo.rb
file.
I think in Python this would be accessible through sys.argv[0]
. One could call __FILE__
however this is not solution I'm looking for, since __FILE__
yields the file inside which the currently execute code lies in.
Is there any way to do that?
If you want to get the path of a file relative to another, you can use the expand_path method with either the constant __FILE__ or the method __dir__ . Read this card for more information about __FILE__ and __dir__ .
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.
Use methods in the File class to manipulate FILE
Inside test.rb, I have
puts __FILE__ puts File.dirname(__FILE__) puts File.basename(__FILE__)
When you run,
ruby a/b/test.rb
You get
a/b/test.rb a/b test.rb
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