It works this way because this is how you want it.
In a case statement, you are trying to fit an object into one of many
different categories. You could try to have every object figure out what
categories it belongs to (terribly difficult), or you could have each
category figure out what belongs in it (easy).
Just look at some examples of case statements:
x = 5
case x
when 4 then …
when 5 then …
…
end
case x
when String then …
when Fixnum then …
…
end
case x
when 0…3 then …
when 3…6 then …
…
end
Imagine trying to code Fixnum#=== with this in mind:
class Fixnum
def === other
if other.kind_of? Fixnum
self == other
elsif other.kind_of? Module
self.kind_of? other
elsif other.kind_of? Range
…
…
end
end
end
You’d almost have to use a case statement! Seem like a bad idea yet? If
not, imagine the code in String#=== or Array#===; most of it would be
identical to what is in Fixnum#===.
Thanks matz. Could you explain why it is done this way?
Well, I’m not Matz, but I’ll give it a shot…
It works this way because this is how you want it.
In a case statement, you are trying to fit an object into one of many
different categories. You could try to have every object figure out what
categories it belongs to (terribly difficult), or you could have each
category figure out what belongs in it (easy).
Just look at some examples of case statements:
x = 5
case x
when 4 then …
when 5 then …
…
end
case x
when String then …
when Fixnum then …
…
end
case x
when 0…3 then …
when 3…6 then …
…
end
Imagine trying to code Fixnum#=== with this in mind:
class Fixnum
def === other
if other.kind_of? Fixnum
self == other
elsif other.kind_of? Module
self.kind_of? other
elsif other.kind_of? Range
…
…
end
end
end
You’d almost have to use a case statement! Seem like a bad idea yet? If
not, imagine the code in String#=== or Array#===; most of it would be
identical to what is in Fixnum#===.