当第一个对象相等时,如何按辅助键对多个对象进行排序?
在我的 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 ofother_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
ornil
.
<=>
的一致实现只有四个允许的返回值:
-
-1
: 小于 -
0
: 相等 -
+1
: 大于 -
nil
: 无与伦比(部分订购)
您没有返回这四个中的任何一个,您返回的是 Array
.与往常一样,如果您违反契约(Contract),可能会发生奇怪的事情。
关于ruby - 当第一个相等时按辅助键对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58586912/