Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Integer.respond_to?(:even?) returns false?

Tags:

ruby

I've been going over the Ruby Koans and I've found the about_open_classes.rb koan interesting. Specially the last test where they modify Integer#even? method. I wanted to play around with this concept so I opened Irb and tried running Integer.respond_to?(:even?), but to my surprise I got false. Then I tried Fixnum.respond_to?(:even?) and got false. I also tried Integer.respond_to?(:respond_to?) and got true and when I do 2.even? I get true too. I have no idea what is going on. Can anyone tell what I'm missing?

like image 813
cmejia Avatar asked Sep 20 '13 13:09

cmejia


1 Answers

An instance of Fixnum will respond_to? :even?, but the Fixnum class itself will not

>> 3.respond_to? :even?
=> true

>> 3.class
=> Fixnum

>> Fixnum.respond_to? :even?
=> false

>> Fixnum.class
=> Class

You can see how this works by defining your own test class:

class Test
  def self.a
    "a"
  end
  def b
    "b"
  end
end

>> Test.respond_to? :a
>> true
>> Test.respond_to? :b
>> false

>> t = Test.new
>> t.respond_to? :a
>> false
>> t.respond_to? :b
>> true
like image 114
New Alexandria Avatar answered Nov 17 '22 18:11

New Alexandria