英文:
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'
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论