排序基于属性的阵列可能在一些元素零 [英] Sorting an array based on an attribute that may be nil in some elements
问题描述
我有对象的数组
并[d#A星= 1 VAL = 1&GT中,<#A星=零VAL = 3> ,与所述; #a的星= 2 VAL = 2]的计算值
我需要数组按时间进行排序,然后通过VAL
并[d#A星= 2 VAL = 2>中<#A星= 1 VAL = 1&GT中,<#A星=零VAL = 3> ]
但使用sort_by,因为时间是零抛出一个错误。
我使用的是丑陋的方式,现在进行排序,但我肯定有一个很好的方式去了解它。
出演= []
@ answers.each {| A | (出演<< A)如果a.starred}
@答案= @回答星级
出演= {starred.sort_by | A | a.starred} .reverse
@答案=出演+ @答案
starred.sort_by {| A | [一个 ? 1:0,一]}
当它必须比较两个元素,它比较了阵列。当红宝石比较阵列(呼叫 ===
法),它比较第1元件,并进入到第二元件只有在第1次是相等的。 ? 1:0
garantees,我们将不得不为长整数元素一号,所以它应该是没有错误
如果您? 0:1
,无
将出现在阵,而不是开始时的最后结果。
下面是一个例子:
IRB> [2,5,1,零,7,3,零,零,4,6] .sort_by {| I | [一世 ? 1:0,I]}
= GT; [零,零,零,1,2,3,4,5,6,7]IRB> [2,5,1,零,7,3,零,零,4,6] .sort_by {| I | [一世 ? 0:1,I]}
= GT; [1,2,3,4,5,6,7,零,零,零]
I have an array of objects
[<#a star=1 val=1>, <#a star=nil val=3> , <#a star=2 val=2>]
i need the array to be sorted by time, then by val
[ <#a star=2 val=2>, <#a star=1 val=1>, <#a star=nil val=3> ]
but using the sort_by throws an error because the time is nil.
I am using an ugly way to sort right now, but i am sure there is a nice way to go about it
starred=[]
@answers.each {|a| (starred << a) if a.starred }
@answers=@answers-starred
starred=starred.sort_by {|a| a.starred }.reverse
@answers=starred+@answers
starred.sort_by { |a| [a ? 1 : 0, a] }
When it has to compare two elements, it compares an arrays. When Ruby compares arrays (calls ===
method), it compares 1st element, and goes to the 2nd elements only if the 1st are equal. ? 1 : 0
garantees, that we'll have Fixnum as 1st element, so it should be no error.
If you do ? 0 : 1
, nil
will appear at the end of array instead of begining.
Here is an example:
irb> [2, 5, 1, nil, 7, 3, nil, nil, 4, 6].sort_by { |i| [i ? 1 : 0, i] }
=> [nil, nil, nil, 1, 2, 3, 4, 5, 6, 7]
irb> [2, 5, 1, nil, 7, 3, nil, nil, 4, 6].sort_by { |i| [i ? 0 : 1, i] }
=> [1, 2, 3, 4, 5, 6, 7, nil, nil, nil]
这篇关于排序基于属性的阵列可能在一些元素零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!