这是我的 ruby 代码:
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)
- 当 firstbook = "Charlie and the Chocolate Factory" 时,secondbook 应该是 "War and Peace" 但代码选择 "Utopia"进行比较。为什么?
最佳答案
确保从传递给 sort!
的 block 中返回比较结果。
目前,您返回 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
}
一切都会正常进行。
题外话,一些吹毛求疵:
- 在Ruby 中,约定是在变量名中用下划线分隔单词。例如,您应该重命名
firstBook
->first_book
- 命名变量时应该非常小心。变量
boolean_value
在这里有点误导,因为它不是true
或false
,它的-1
,0
,或1
。
关于Ruby:字符串与字符串的比较失败(ArgumentError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26989922/