In Ruby, how does a class defined in a module know the module's constants?

被刻印的时光 ゝ 提交于 2019-12-05 01:00:29

问题


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.


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!