Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between '.' and File.dirname(__FILE__) in RUBY

Tags:

ruby

I am working my way through a Lynda.com Ruby course and building a small app. In order to make the file portable, the teacher uses this form below.

APP_ROOT = File.dirname(__FILE__)

I understand the purpose of the constant FILE as it always resolves the current file no matter what its name.

When I type p APP_ROOT it resolves to a . # => '.' which I understand represents this current directory.

What I don't get is why, if File.dirname(__FILE__) always == '.', why not just use '.' ?

For example the output of:

$LOAD_PATH.unshift( File.join(APP_ROOT, 'lib'))

p $:

is equal to

$LOAD_PATH.unshift( File.join('.', 'lib'))

p $:

when I p $: I get the same exact results for either line. What is the value of File.dirname(__FILE__) over '.' ?

Also, I searched all over but I'm not sure. If I am in directory /home/one/apps

If I enter '.' is that equal to the apps directory OR does that mean the entire absolute path including the final directory? so . is really /home/ones/apps not just /apps

Thanks in advance.

like image 219
Qstreet Avatar asked Jun 16 '18 14:06

Qstreet


1 Answers

File.dirname(__FILE__) isn’t always the same as the current directory. It will be the same if you start your Ruby program from the same directory as the file, but will be different if you start from a different directory.

For example if you have a subdirectory subdir containing foo.rb with the contents:

puts File.dirname(__FILE__)

then running from parent directory you get this:

$ ruby subdir/foo.rb
subdir

but if you cd into the directory and then run the file you get this:

$ cd subdir
$ ruby foo.rb
.
like image 176
matt Avatar answered Sep 20 '22 20:09

matt