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` .

···

--
Posted via http://www.ruby-forum.com/.

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

···

--
Posted via http://www.ruby-forum.com/.

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

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` .

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

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

···

On Wed, 29 Jan 2014 15:52:43 +0100 Arup Rakshit <lists@ruby-forum.com> wrote:

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

--
Sergey Avseyev

Sergey Avseyev wrote in post #1134821:

···

On Wed, 29 Jan 2014 15:52:43 +0100 > Arup Rakshit <lists@ruby-forum.com> 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!

--
Posted via http://www.ruby-forum.com/\.