0

Can someone please explain me why this can be happening

$ irb
2.1.1 :001 > "9" > "3"
 => true 
2.1.1 :002 > "10" > "3"
 => false 
2.1.1 :005 > "2.3" > "2.1"
 => true
2.1.1 :003 > 

Why is "10" > "3" returning false ?

AnkitG
  • 6,438
  • 7
  • 44
  • 72

2 Answers2

1

Because in all these cases Strings are compared, not Numbers. And when Strings are compared, it's done character-by-character. Apparently, character "1" is 'less' than character "3".

raina77ow
  • 103,633
  • 15
  • 192
  • 229
0

String class included Comparable module. Thus in each tests, you are performing, actually calling Comparable#> method, which in turn calls String#<=> method.

Why "10" > "3" returns true ?

First see the doc - If the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered greater than the shorter one.

Now in your case, yes, '10' and '3' are of different size. But the strings are not equal when compared up to the shortest length, thus longer string is not considered greater than the shorter one. It means 1 from longer string, is not equal '3' from the shortest string. This equality is performed by String#eql?.

Now again consider the example "10" > '1', it return true, as the strings are equal when compared up to the shortest length, thus longer string is considered greater than the shorter one.

But when strings are having equal size, then comparisons are made character by character, using String#eql? method.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317