[英]In Ruby, how does a class defined in a module know the module's constants?
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. 我知道这很明显,但是由于Wheel在Seat的层次结构中不存在,所以我不知道它如何访问它。
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. 如果您引用一个类常量,则Ruby将首先在同一模块中查找它,然后在根中找不到它。
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
. 因此,由于
Seat
和Wheel
都在Car
模块中,因此,如果您查找Wheel
,它将首先查找Car::Wheel
,然后查找::Wheel
。 Since Car::Wheel
exists, you get that reference. 由于
Car::Wheel
存在,因此您可以获得该引用。
You are looking for information on Ruby's Constant Lookup rules. 您正在寻找有关Ruby的常量查找规则的信息。 Details surrounding this changed in Ruby 1.9, and then changed again in Ruby 1.9.2.
围绕它的详细信息在Ruby 1.9中进行了更改,然后在Ruby 1.9.2中再次进行了更改。 You can read some discussion on this on the ruby-core mailing list.
您可以在ruby-core邮件列表上阅读有关此内容的一些讨论 。
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 这是对Ruby 1.8.x,Ruby 1.9和Ruby 1.9.2之间的一些差异的出色回顾: http : //jfire.posterous.com/constant-lookup-in-ruby
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.