为什么数字字符串比较会产生意想不到的结果? [英] Why do numeric string comparisons give unexpected results?

查看:46
本文介绍了为什么数字字符串比较会产生意想不到的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

谁能解释一下为什么上面例子中的结果是正确的?如果我只是比较 '1:' 和 '2:' 我会得到预期的结果:

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

推荐答案

字符串按字符比较.

当您比较 1:2: 时,比较以 21 开始,并且与预期结果的比较就到此为止.

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

当您比较 1:10: 时,比较以 11 开始,并且由于这是平局,比较继续进行下一个比较,即 :0,比较在那里停止,结果出乎您的意料(考虑到您的期望比较字符串中的整数).

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_i 将两个操作数都转换为整数.

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

这篇关于为什么数字字符串比较会产生意想不到的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆