69

In Ruby 2.0.0-p0, the __dir__ variable was introduced for easy access to the directory of the file currently being executed.

Why is __dir__ lowercase when __FILE__ is uppercase?

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
conradkleinespel
  • 6,560
  • 10
  • 51
  • 87
  • 7
    `__FILE__` is constant and `__dir__` is method: http://permalink.gmane.org/gmane.comp.lang.ruby.core/52295 – SwiftMango Mar 03 '13 at 20:53
  • ```__FILE__``` is not a constant. According to ```Kernel.const_get``` it is not even a valid name for a constant. – Pascal Jan 11 '16 at 20:15

2 Answers2

70

I think that is because __FILE__ is a parse-time constant whereas __dir__ is a function and returns File.dirname(File.realpath(__FILE__))

For more details, see This discussion

notapatch
  • 6,569
  • 6
  • 41
  • 45
Intrepidd
  • 19,772
  • 6
  • 55
  • 63
38

TL; DR

The relative merits of language implementation choices are outside the scope of a reasonable Stack Overflow question. However, this is a good question because it identifies a potentially confusing use case in the language and seeks to clarify the distinction between the two language elements.

Keywords, Methods, and Keywords That Look Like Methods

__FILE__ is a Keyword

In Ruby 1.9, __FILE__ is a keyword. Even though it looks like a method defined on the Object class, the source for Object#__FILE__ says:

# File keywords.rb, line 68
def __FILE__
end

A quick scan of the source in 2.0.0-p0 didn't turn up a keywords.rb file, but one assumes that __FILE__ syntactically remains a keyword. Perhaps someone else can point you to the location of the current definition.

__dir__ is a Method

Kernel#__dir__ is actually a method. You can see this for yourself by grepping the Kernel's defined methods:

Kernel.methods.grep /__dir__/
# => [:__dir__]

Bugs and Discussions

The fact that __FILE__ is both a keyword and (sort of) a method is called out in a bug and some bug-related commentary. There was also discussion of the various pros and cons of the naming convention in the Ruby-Core Forum.

While the answer may be a bit unsatisfactory, that's the current state of affairs. If it's a language design issue you feel strongly about, getting involved with the Ruby core team would be the proper way to address it.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • 4
    The keywords table is defined in [defs/keywords](https://github.com/ruby/ruby/blob/trunk/defs/keywords#L13) (and interestingly, hasn't changed for four years) – dbenhur Mar 04 '13 at 01:44