Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using sort_by in ruby (for rails)?

Tags:

So I've built a custom array of users like such:

[["user1",432],["user1",53],["user9",58],["user5",75],["user3",62]]

I want to sort them by the 2n'd value in each array, from largest to smallest. I have a feeling using sort or sort_by for arrays is the way to do this, but I'm not really sure how to accomplish it

like image 398
Elliot Avatar asked Feb 05 '12 09:02

Elliot


1 Answers

sort_by

If you're interested in sort_by, you could destructure your inner arrays

array.sort_by { |_, x| x }.reverse

or call the index operator

array.sort_by { |x| x[1] }.reverse

Instead of reversing you could negate values returned from the block.

array.sort_by { |_, x| -x }
array.sort_by { |x| -x[1] }

Yet another alternative would be to use an ampersand and Array#last.

array.sort_by(&:last).reverse

sort

A solution using sort could be

array.sort { |x, y| y[1] <=> x[1] }
like image 94
Jan Avatar answered Sep 22 '22 13:09

Jan