ruby - 当第一个相等时按辅助键对对象进行排序

标签 ruby

当第一个对象相等时,如何按辅助键对多个对象进行排序?

在我的 Book 类中,我使用以下方法进行排序

def <=>(other)
  printed_on <=> other.printed_on
end

现在我需要将当天打印的书籍 (printed_on = other.printed_on) 按 page_number 排序。

因为sort_by你可以传递一个键数组,我试过了

 def <=>(other)
   [printed_on <=> other.printed_on, page_number <=> other.page_number]
 end

但是我明白了

undefined method `>' for [1, 1]:Array

最佳答案

Array s are compared lexicographically (大胆强调我的):

Arrays are compared in an “element-wise” manner; the first element of ary is compared with the first one of other_ary using the <=> operator, then each of the second elements, etc… As soon as the result of any such comparison is non zero (i.e. the two corresponding elements are not equal), that result is returned for the whole array comparison.

[这只是一种令人费解的说法,即“Array 是按字典顺序比较的”。]

所以你可以简单地使用 Array供您比较:

def <=>(other)
  [printed_on, page_number] <=> [other.printed_on, other.page_number]
end

你的方法违反了the contract of <=> (大胆强调我的):

Your implementation of #<=> should return one of the following values: -1, 0, 1 or nil.

<=> 的一致实现只有四个允许的返回值:

  • -1 : 小于
  • 0 : 相等
  • +1 : 大于
  • nil : 无与伦比(部分订购)

您没有返回这四个中的任何一个,您返回的是 Array .与往常一样,如果您违反契约(Contract),可能会发生奇怪的事情。

关于ruby - 当第一个相等时按辅助键对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58586912/

相关文章:

ruby - 提交时生成文档

ruby - 什么是 SSH 转发?

ruby - 调试最长递增子序列 - Ruby

ruby - 当路径在 Ruby 中已知时取消链接 Tempfile

ruby-on-rails - 从作为引擎安装的 gem 重载 lib 文件

ruby-on-rails - ruby rails : undefined method 'before_save'

ruby-on-rails - ruby rails : Passing argument to singleton

ruby-on-rails - 使用 Ruby on Rails 访问 Google Drive API v3

ruby-on-rails - 在 Label 标签中嵌套 Ruby on Rails HAML 复选框

ruby-on-rails - rvm,将 gemset 关联到项目