gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:59:41 27 4
gpt4 key购买 nike

这是我的 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}"

}

问题:

  1. 此代码运行单次迭代,然后给出错误 in 'sort!': Comparison of String with String failed (ArgumentError)
  2. 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 在这里有点误导,因为它不是 truefalse,它的 -10,或 1

关于Ruby:字符串与字符串的比较失败(ArgumentError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26989922/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com