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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With