单引号字符串的 Ruby 排序

huangapple go评论60阅读模式
英文:

ruby sort of single quoted strings

问题

为什么 Ruby 中单引号括起来的字符串排序会出错?

a=["'string 1'","'string 1 x'"]
# => ["'string 1'", "'string 1 x'"]
a.sort
# => ["'string 1 x'", "'string 1'"]

我正在使用 Ruby 2.7.4p191。

英文:

Why does ruby sort of single quoted strings go wrong?

a=["'string 1'","'string 1 x'"]
# => ["'string 1'", "'string 1 x'"]
a.sort
# => ["'string 1 x'", "'string 1'"]

I am using ruby 2.7.4p191.

答案1

得分: 8

结果是正确的,符合预期。字符串的长度并不重要,字符串按字典顺序进行比较 - 每个字符都与另一个字符串相同位置的字符进行比较。空格字符(ASCII 32)在单引号字符(ASCII 39)之前,所以 'string 1 x' 实际上是比 'string 1'“小”的。

英文:

The result is not wrong, it's what it should be expected. Length of the strings doesn't matter, and strings are compared lexicographically - each character is compared to the character on the same position in the other string. The space character (ASCII 32) comes before the single quote character (ASCII 39), so 'string 1 x' is actually "less than" 'string 1'.

huangapple
  • 本文由 发表于 2023年5月10日 18:42:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76217439.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定