关于 Ruby 中的类定义
最近,我正在研究 Ruby 中类的一些细节,并对类定义感到困惑。
在Ruby中,类定义如下,
class A
def self.my_method
end
end
一样
class A
class << self
def my_method
end
end
end
和当时我很困惑的 。对于第一种情况,self可以被视为指向当前使用的对象的指针,上下文的当前类是A。并且方法查找是递归完成的。但我的问题是, def 是做什么的?它如何改变当前的对象和上下文?第二种情况的问题是相同的。 class << 之类的描述如何? self 改变当前对象和上下文?
还有一个问题。据我所知,所有 Class 对象都遵循像 Fly-weight 这样的设计模式,因为它们共享具有相同定义的相同 Class 对象。然后特征类就变得混乱了。既然eigenclass中的def实际上是用Class对象定义了一个方法,那么它怎么会与“def self.*”相关呢?
从外面看起来太复杂了,我可能需要Ruby的设计细节。
Recently, I was investigating into some details about classes in Ruby, and was confused by class definition.
In Ruby, the class definition is as follows,
class A
def self.my_method
end
end
and it's the same as
class A
class << self
def my_method
end
end
end
then I was confused. For the 1st case, self can be regarded as a pointer to currently using object, and current class of the context is A. And the method looking-up is done recursively. But my question is, what does def do? How does it change the current object and context? The problem is same for the 2nd case. How does the description like class << self change the current object and context?
And another question. As far as I know, all Class objects are obeying design patterns like fly-weight, since they share the same Class object with same definition. Then the eigenclass became confusing. Since the def in a eigenclass actually defines a method with Class object, how can it be related to "def self.*"?
It looks too complicated from the outside, and I may need the design details of Ruby.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是相同的:
还有这个:
还有这个:
你可以打开任何东西的特征类:
特征类实际上是 Class 的一个实例,它也有自己的特征类。
This is the same:
And this:
And also this:
You can open the eigenclass of anything:
An eigenclass is actually an instance of Class, it has it own eigenclass too.