0

I've been studying ruby and frameworks like Sinatra and Rails, and I see this kind of code:

File.expand_path(..., __FILE__) # this returns something like /Users/.../app/something.rb

Instead of just starting from:

File.expand_path(..., ".") # this returns something like /Users/.../app

Since both return valid and known paths, is there any reason to start navigating from __FILE__ instead of "."?

Thanks in advance.

  • possible duplicate of [What does \_\_FILE\_\_ mean in Ruby?](http://stackoverflow.com/questions/224379/what-does-file-mean-in-ruby) – Pavan May 03 '14 at 08:41

2 Answers2

4

__dir__ or (__FILE__) is not necessarily the same as ".". The former is the location of the file. The latter is the location from where the main command was called (or wherever it was changed to by commands like Dir.chdir).

sawa
  • 165,429
  • 45
  • 277
  • 381
0

__FILE__ represents the current file, whereas '.' represents the current directory of code execution. So, you have to go a level (..) before the current file to reach to a particular file as compared to '.'.

From what I have read, it is sort of ugly way of using it. Developers use it as per intuition and it's entirely upto to conventions adopted by project/community.

Community
  • 1
  • 1
kiddorails
  • 12,961
  • 2
  • 32
  • 41
  • Your link is outdated. The point is that `__FILE__` requires extra `..`, which makes it tricky. But in modern Ruby, `__dir__` should be used to avoid that problem. – sawa May 03 '14 at 08:47
  • Hm. Agreed. Didn't know about the `__dir__` idiom. Maybe, `__FILE__` is still being used in some projects to support back compatibility to previous Ruby versions. – kiddorails May 03 '14 at 08:49