Oscar Rodriguez
Oscar Rodriguez

Reputation: 33

Why do numeric string comparisons give unexpected results?

'10:' < '1:'
# => true

Can someone explain me why the result in the above example is true? If I just compare '1:' and '2:' I get the result expected:

'1:' < '2:'
# => true

Upvotes: 2

Views: 90

Answers (4)

user513951
user513951

Reputation: 13612

Strings are compared character by character.

When you compare 1: vs 2:, the comparison begins with 2 vs 1, and the comparison stops there with the expected result.

When you compare 1: vs 10:, the comparison begins with 1 vs 1, and since it is a tie, the comparison moves on to the next comparison, which is : vs 0, and the comparison stops there with the result that you have found surprising (given your expectation that the integers within the strings would be compared).

To do the comparison you expect, use to_i to convert both operands to integers.

Upvotes: 2

Alok Anand
Alok Anand

Reputation: 3356

It is character by character comparison in ASCII.

'10:' < '1:' is (49 < 49) || (48 < 58) || (58 < ?)

#=> true

'1:' < '2:' is (49 < 50) || (58 < 58)

#=> true

Left to Right boolean check is used and check breaks where true is found.

Note: It is just my observation over various example patterns.

Upvotes: 1

sawa
sawa

Reputation: 168071

Because the ASCII code for 0 is 48, which is smaller than the ASCII code for :, which is 58.

Upvotes: 0

Tim Destan
Tim Destan

Reputation: 2028

The first character of each of your two strings are the same. And as Dave said in the comments, the second character of the first, '0', is less than ':', so the first string is less than the second.

Upvotes: 0

Related Questions