Why is the string '3' not matched in a case statement with the range ('0'…'10')?

28

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"]
Share
Improve this question
New contributor
jockofcode is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
2
  • TL;DR: Dictionary order is not the same as string-converted-to-a-number order. – Dave Newton Apr 23 at 17:32
  • If your range isn't that large, you can use 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

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

React Native - Image Cache