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)
问题:
in 'sort!': comparison of String with String failed (ArgumentError)确保从传递给的块中返回比较结果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)
一切都会成功。
题外话,说几个小毛病:
firstBook->first_bookboolean_value在这里有点误导,因为它不是trueor false,而是-1, 0, or 1。| 归档时间: |
|
| 查看次数: |
12516 次 |
| 最近记录: |