Confusion with Object#respond_to?

Code :

irb(main):001:0> class Animal
irb(main):002:1> def bark;end
irb(main):003:1> end
=> nil
irb(main):004:0> class Object
irb(main):005:1> def foo;end
irb(main):006:1> end
=> nil
irb(main):007:0> Animal.respond_to?(:bark)
=> false
irb(main):008:0> Object.respond_to?(:foo)
=> true
irb(main):009:0>

My question is -

I can see foo is an instance method of Object. If so Why does
Object.respond_to?(:foo) return true ?

if I understand this Animal.respond_to?(:bark) # => false, I can’t
understand Object.respond_to?(:foo) # => true .

Object is a special case.
My advice is, don’t modify it!

On Wed, 29 Jan 2014 15:52:43 +0100
Arup R. [email protected] wrote:

if I understand this Animal.respond_to?(:bark) # => false, I can’t
understand Object.respond_to?(:foo) # => true .

1.9.3p484 (main):001:0> Object.is_a?(Class)
true
1.9.3p484 (main):002:0> Class.is_a?(Object)
true

Because Object inherits from Class and Class inherits from the Object

Sergey Avseyev wrote in post #1134821:

On Wed, 29 Jan 2014 15:52:43 +0100
Arup R. [email protected] wrote:

if I understand this Animal.respond_to?(:bark) # => false, I can’t
understand Object.respond_to?(:foo) # => true .

1.9.3p484 (main):001:0> Object.is_a?(Class)
true
1.9.3p484 (main):002:0> Class.is_a?(Object)
true

Because Object inherits from Class and Class inherits from the Object

This part in Ruby is very confusing to me… :frowning:

Thanks for the answer!

Excerpts from Arup R.'s message of 2014-01-29 15:52:43 +0100:

irb(main):007:0> Animal.respond_to?(:bark)
if I understand this Animal.respond_to?(:bark) # => false, I can’t
understand Object.respond_to?(:foo) # => true .

Because everything in ruby is an instance of Object, including instances
of class Class
(that is, including classes). Since your foo method is an instance
method of
Object, it can be called on everything. You can check this by calling:
Animal.foo. It
won’t raise exceptions.

I hope this helps

Stefano

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs