Confusing File.dirname Behavior

I have written some small Ruby scripts for system administration using Ruby 1.9.3. In one script, I use:

File.dirname(__FILE__) 

to get the directory of the script file. This returns the relative path, however, when I call the script from the second script File.dirname , the absolute path is returned.

The Ruby Doc lists the absolute return path in my example, whereas I found a discussion on the Ruby Forum where the user says that dirname should only return a relative path.

I use the proposed solution from the Ruby Forums to use File.expand_path to always get the absolute path as follows:

 File.expand_path(File.dirname(__FILE__)) 

but is there a way to make dirname behavior consistent?


UPDATE:

To extend the answer to Janathan Cairs, I made two scenarios:

s1.rb:

 puts "External script __FILE__: #{File.dirname(__FILE__)}" 

s0.rb:

 puts "Local script __FILE__: #{File.dirname(__FILE__)}" require './s1.rb' 

Running. / S0.rb gives the following result:

 Local script __FILE__: . External script __FILE__: /home/kenneth/Pictures/wp/rip_vault 
+4
source share
2 answers

File.dirname should return an absolute path if an absolute path is given, and a relative path if a relative path is given:

 File.dirname('/home/jon/test.rb') # => '/home/jon' File.dirname('test.rb') # => '.' 

__FILE__ returns the name of the current script, which is the relative path from the current directory. This means that you should always use expand_path if you want to get the absolute path using File.dirname(__FILE__) .

NB Ruby 2.0.0 introduces the __dir__ constant

+7
source

If you have already upgraded to Ruby 2.0 , you can use the new constant

 __dir__ 

otherwise you can use

 File.expand_path('..', __FILE__) 

which is shorter

 File.expand_path(File.dirname(__FILE__)) 

Documentation File.expand_path

+3
source

All Articles