这是我的红宝石代码:
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}"
}
问题:
in 'sort!': comparison of String with String failed (ArgumentError)
答案 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,一些挑剔:
firstBook
- &gt; first_book
boolean_value
在这里有点误导,因为它不是true
或false
,而是-1
,0
或1
。