loganhasson
loganhasson

Reputation: 1180

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?

Upvotes: 3

Views: 93

Answers (1)

Alex.Bullard
Alex.Bullard

Reputation: 5563

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

Upvotes: 4

Related Questions