Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - get the file being executed

Tags:

ruby

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?

like image 381
Victor Blaga Avatar asked Dec 20 '11 14:12

Victor Blaga


People also ask

How do I get the file path in Ruby?

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__ .

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.


1 Answers

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 
like image 62
peakxu Avatar answered Oct 05 '22 22:10

peakxu