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
Use sort_by
for these things, not sort
!
array.sort_by {|h| [h[:accepts] ? 0 : 1,h[:id]]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With