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

标签 ruby string sorting comparison

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

相关文章:

c - 在 C 中对递增列表进行排序

ruby-on-rails - Ruby 在数组中排序哈希时遇到问题

ruby - 如何让Ruby捕获线程中的语法错误

python - 找出字符连续的最长子串,这里的字符串可能是乱码

c++ - C++ 中的字符串比较是如何工作的?

c++ - 未知类型名称字符串 C++

graphics - 对一维颜色列表进行排序?

python - 按一列上的另一个数据框对数据框进行排序 - pandas

ruby - 事件驱动的应用程序 - 选择什么语言或 VM?

php - 从 PHP 执行 Ruby 脚本并获取输出