Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a ruby array in ascending order but keep zero last

I am trying to sort a Ruby array with the following function

@prices = @item.prices.sort { |x,y| x.total <=> y.total }

Which orders from the lowest to the highest cost. However some products have a total of 0.00 and I want them to appear last rather than at the top.

I have tried a few things but would like some way to modify this block to sort zero at the bottom but keep the rest in ascending order.

Thanks.

like image 356
Nick Barrett Avatar asked Sep 01 '25 16:09

Nick Barrett


2 Answers

Try this out, I think it is doing what you request:

@prices = @item.prices.sort {|a,b| a.total==0 ? 1 : b.total==0 ? -1 : a.total<=>b.total}
like image 124
ctcherry Avatar answered Sep 04 '25 22:09

ctcherry


Just for the record:

>> 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]

On most platforms 1.0/0 will evaluate to Infinity, so you can also use this instead of 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]
like image 22
Michael Kohl Avatar answered Sep 04 '25 21:09

Michael Kohl