I'm trying to understand how a class defined in a module knows the module's constants. Here's an example of what I mean:
module Car
class Wheel
end
class Seat
p Wheel # Car::Wheel
end
end
I know it's obvious, but since Wheel is nowhere in Seat's hierarchy, I don't understand how it can have access to it.
If you reference a class constant, Ruby will look for it first in the same module, and then on the root if it's not found there.
So, since both Seat
and Wheel
are in the Car
module, if you look for Wheel
, it will first look for Car::Wheel
, and then for ::Wheel
. Since Car::Wheel
exists, you get that reference.
You are looking for information on Ruby's Constant Lookup rules. Details surrounding this changed in Ruby 1.9, and then changed again in Ruby 1.9.2. You can read some discussion on this on the ruby-core mailing list.
Here is an excellent review of some of differences between Ruby 1.8.x, Ruby 1.9, and Ruby 1.9.2: http://jfire.posterous.com/constant-lookup-in-ruby
来源:https://stackoverflow.com/questions/4855926/in-ruby-how-does-a-class-defined-in-a-module-know-the-modules-constants