[英]How to sort a ruby array in ascending order but keep zero last
我試圖用以下函數對Ruby數組進行排序
@prices = @item.prices.sort { |x,y| x.total <=> y.total }
哪個訂單從最低到最高成本。 然而,有些產品總共有0.00,我希望它們出現在最后而不是頂部。
我已經嘗試了一些東西但是想要某種方法來修改這個塊以在底部排序零但保持其余的按升序排列。
謝謝。
試試這個,我認為它正在按你的要求做:
@prices = @item.prices.sort {|a,b| a.total==0 ? 1 : b.total==0 ? -1 : a.total<=>b.total}
prices = [0, 1, 2, 0,4, 3]
prices = prices.sort_by do |price|
[
if price == 0
1
else
0
end,
price
]
end
p prices
# => [1, 2, 3, 4, 0, 0]
這里的技巧是通過比較它們的第一個元素來比較數組,但如果這些元素相等,那么通過比較它們的下一個元素,依此類推。 因此,讓sort_by塊生成一個數組可以讓您以干凈的方式確定主排序順序,二級排序順序等。
僅供記錄:
>> a = [0, 1, 3, 0, 2, 5, 0, 9]
=> [0, 1, 3, 0, 2, 5, 0, 9]
>> a.sort_by { |x| x.zero? ? Float::MAX : x }
=> [1, 2, 3, 5, 9, 0, 0, 0]
在大多數平台上, 1.0/0
將評估為Infinity
,因此您也可以使用它而不是Float::MAX
:
>> b = [1,4,2,0,5,0]
=> [1, 4, 2, 0, 5, 0]
>> Inf = 1.0/0
=> Infinity
>> b.sort_by { |x| x.zero? ? Inf : x }
=> [1, 2, 4, 5, 0, 0]
所以設計一個比較器來做到這一點......
if x.total == 0
# always consider 0 "largest" and no 0 can be larger than another
# (make sure 0.0 is 0 and not a number really close to 0)
# perhaps x or y should be first for other reasons as well?
1
else
# otherwise lower to higher as normal
x.total <=> y.total
end
或者沒有評論:
foo.sort {|x, y| if x.total == 0 then 1 else x.total <=> y.total end}
快樂的編碼。
對我來說,這會讓我覺得不那么苛刻,也不那么只寫:
prices = prices.sort_by do |price|
zero_status = price.zero? ? 1 : 0
[zero_status, price]
end
因為這是按照兩個標准對事物進行排序的慣用方法,這就是你在這里做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.