[英]Why does Object, the class, respond to instance methods defined on it?
I ran into this behavior earlier today and was hoping somebody could explain why this happens: 我今天早些时候遇到过这种行为,并希望有人能解释为什么会发生这种情况:
class Object
def some_method
end
end
Object.respond_to?(:some_method) # => true
Of course, this doesn't happen with other classes: 当然,其他类不会发生这种情况:
class Dog
def some_other_method
end
end
Dog.respond_to?(:some_other_method) # => false
So what gives? 什么给出了什么?
This happens b/c Object
is a superclass of Class
itself. 发生这种情况b / c Object
是Class
本身的超Class
。 So class Object
is an instance of Object
(confusing). 所以class Object
的实例Object
(混乱)。 When you define an instance method on Dog
you dont cause the same issue b/c the class Dog
does not appear in the inheritance chain of Class
当您在Dog
上定义实例方法时,不会导致相同的问题b / c类Dog
不会出现在Class
的继承链中
Object.instance_of?(Class) # True
Class.is_a?(Object) # True
Class.is_a?(Dog) # False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.