I’m unable to determine why these two functions behave differently. I could just use symbols or my own constants, but I have a deep desire to know what’s going on here (and if I’m doing something bad).
def convert(value, type)
case type
when Integer
value.to_i
when String
value.to_s
else
value
end
end
def convert_with_if(value, type)
if (type == Integer)
value.to_i
elsif (type == String)
value.to_s
else
value
end
end
n = 4.4
p convert(n, Integer) #=> 4.4
p convert_with_if(n, Integer) #=> 4
casecalls===, the case equality operator.Module#===, and by extensionClass#===, actually tests if the given argument’s class is the receiver or is one of its descendants.String === objectis practically equivalent toobject.kind_of? String.Would be equivalent to:
That’s like asking
is the String class an Integer?, oris the String class a String?. The answer to both questions isNo, it is a Class..In terms of code,
String.classreturnsClass, which is not related in any way toIntegeror evenStringitself. If you introduced awhen Classorwhen Moduleclause, it would be executed every time.