Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby sort by boolean and number

I'm using Ruby 1.8.7. I have the following array of hashes. I need to sort by the boolean value first, but those results must be ordered as well in the original order. I basically need to shift all the true hashes to the top of the array but maintain the original ordering.

Any help would be appreciated!

array = [{:id => 1, :accepts => false}, 
         {:id => 2, :accepts => false}, 
         {:id => 3, :accepts => true}, 
         {:id => 4, :accepts => false}, 
         {:id => 5, :accepts => true}]

sorted = array.sort do |x, y|
  if x[:accepts] == y[:accepts]
    0
  elsif x[:accepts] == true
    -1
  elsif x[:accepts] == false
    1
  end
end

This sort that I have yields:

5 - true
3 - true
2 - false
4 - false
1 - false

I need it to yield:

3 - true
5 - true
1 - false
2 - false
4 - false

like image 314
Nick Avatar asked Nov 03 '10 20:11

Nick


1 Answers

Use sort_by for these things, not sort!

array.sort_by {|h| [h[:accepts] ? 0 : 1,h[:id]]}
like image 129
glenn mcdonald Avatar answered Oct 20 '22 20:10

glenn mcdonald