Ruby:String与String的比较失败(ArgumentError)

时间:2014-11-18 08:40:32

标签: ruby string sorting 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}"

}

问题:

  1. 此代码运行单次迭代,然后出现错误in 'sort!': comparison of String with String failed (ArgumentError)
  2. firstbook =&#34; Charlie和巧克力工厂&#34; 然后 secondBook应该是&#34; War and Peace&#34; 但是代码选择的&#34;乌托邦&#34;比较。为什么?

1 个答案:

答案 0 :(得分:3)

确保从传递给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
}

一切都会奏效。


Offtopic,一些挑剔:

  • 在Ruby中,惯例是在变量名中用下划线分隔单词。例如,您应该重命名firstBook - &gt; first_book
  • 在命名变量时应该非常小心。变量boolean_value在这里有点误导,因为它不是truefalse,而是-101