سؤال

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. So class Object is an instance of Object (confusing). 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

Object.instance_of?(Class) # True
Class.is_a?(Object) # True
Class.is_a?(Dog) # False
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top