Ruby:字符串与字符串的比较失败(ArgumentError)

pau*_*aul 4 ruby sorting string comparison

这是我的红宝石代码:

books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]

books.sort! {

  |firstBook, secondBook|
  boolean_value = firstBook <=> secondBook
  print "first book is =  '#{firstBook}'"
  print " , second book is = '#{secondBook}'"
  puts  " and there compare result is #{boolean_value}"

}
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 此代码运行单次迭代,然后给出错误in 'sort!': comparison of String with String failed (ArgumentError)
  2. 第一本书=“查理和巧克力工厂”时,第二本书应该是“战争与和平”,但它的代码选择“乌托邦”进行比较。为什么?

Cri*_*scu 5

确保从传递给的块中返回比较结果sort!

目前,您返回nil(最后一个语句的返回值puts),这会导致不可预测的结果。

将您的代码更改为:

books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]

books.sort! {

  |firstBook, secondBook|
  boolean_value = firstBook <=> secondBook
  print "first book is =  '#{firstBook}'"
  print " , second book is = '#{secondBook}'"
  puts  " and there compare result is #{boolean_value}"

  boolean_value  # <--- this line has been added
}
Run Code Online (Sandbox Code Playgroud)

一切都会成功。


题外话,说几个小毛病:

  • 在 Ruby 中,惯例是在变量名称中用下划线分隔单词。例如,您应该重命名firstBook->first_book
  • 命名变量时应该非常小心。该变量boolean_value在这里有点误导,因为它不是trueor false,而是-1, 0, or 1

  • @paul 我不太清楚,但如果我大胆猜测,我会说 Ruby 在幕后使用 QuickSort,并且 *Utopia* 被选为快速排序枢轴。[显然中间元素是枢轴的合理候选者](http://stackoverflow.com/a/164177/390819)。 (2认同)