Why is the string '3' not matched in a case statement with the range ('0'…'10')?
When I try to match for the string '3' in a case statement, it matches if the range goes up to '9', but not '10'.
I'm guessing it has something to do with the triple equals operator, but I don't know the exact reason why it can be in the range, but not matched.
Here is an IRB run documenting both cases that work (with '9'), and don't work (with '10'):
case '3'
when ('0'...'9')
puts "number is valid"
else
puts "number is not valid"
end
Output: number is valid
case '3'
when ('0'...'10')
puts "number is valid"
else
puts "number is not valid"
end
Output: number is not valid
The methods that I used as a reference for the expected results are
Enumerable#include?
Enumerable#member?
and seeing what is output when converted to an array is (Enumerable#to_a
).
The result of the "case equality" (===
) operator surprised me.
puts ('0'...'10').include?('3')
# => true
puts ('0'...'10').member?('3')
# => true
puts ('0'...'10') === '3'
# => false
puts ('0'...'10').to_a
# => ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
when *'0'...'10'
which turns your range into an argument list, i.e.when '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
. – Stefan Apr 25 at 10:34