Why do numeric string comparisons give unexpected results?

后端 未结 4 1586
生来不讨喜
生来不讨喜 2021-01-15 15:59
\'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

4条回答
  •  感动是毒
    2021-01-15 16:36

    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.

提交回复
热议问题