1.day Ruby's case operator === behaved badly

By: Johnathon Wright on: May 29, 2009

This is a follow-up to a previous post about the Ruby case operator, ===.

I previously understood that, for a === b where a is a class, the result would be b.class.ancestors.include?(a)

when a is an instance, the result would be a == b

This proves true for many examples.

---ruby

3.class.ancestors.all? {|a| a === 3}

=> true

So I was very suprised to find this:

---ruby

3.days.class => Fixnum

Fixnum === 3.days => False

3.days.class.ancestors.include?(Fixnum)

=> true

---ruby def days ActiveSupport::Duration.new(self * 24.hours, [[:days, self]])

end

And, in fact: ---ruby

ActiveSupport::Duration === 3.days

=> true

I'm not clear on why this happens. I'll update this post as it becomes clear.





Comments:

Just checking that you are human. What would be the result of this code?

a = 3*(4/2); b = 1; a+b

Back