Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby sort array of an array

I'm having a problem figuring out how I can sort an array of an array. Both arrays are straight forward and I'm sure it's quite simple, but I can't seem to figure it out.

Here's the array:

[["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]

I want to sort it by the integer value of the inner array which is a value of how many times the word has occurred, biggest number first.

like image 220
ere Avatar asked Mar 08 '12 10:03

ere


People also ask

How do you sort an array of arrays in Ruby?

You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)

How do you sort an array of elements in Ruby?

The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.


1 Answers

Try either:

array = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
sorted = array.sort {|a,b| a[1] <=> b[1]}

Or:

array = [["happy", 1], ["sad", 2], ["mad", 1], ["bad", 3], ["glad", 12]]
sorted = array.sort {|a,b| b[1] <=> a[1]}

Depending if you want ascending or descending.

like image 151
Edu Avatar answered Sep 29 '22 12:09

Edu