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