Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by a value in an object in an array in Ruby

I have a bunch of objects in an array and would like to sort by a value that each object has. The attribute in question in each object is a numeric value.

For example:

[[1, ..bunch of other stuff],[5, ""],[12, ""],[3, ""],]

would become:

[[1, ..bunch of other stuff],[3, ""],[5, ""],[12, ""],]

I want to sort by the numerical value stored in each of the objects.

[5, 3, 4, 1, 2] becomes [1, 2, 3, 4, 5], however these numbers are stored inside objects.

like image 285
Julio Avatar asked Dec 10 '22 09:12

Julio


2 Answers

The other answers are good but not minimal. How about this?

lst.sort_by &:first
like image 185
Peter Avatar answered Dec 26 '22 00:12

Peter


The sort method can take a block to use when comparing elements:

lst = [[1, 'foo'], [4, 'bar'], [2, 'qux']]
=> [[1, "foo"], [4, "bar"], [2, "qux"]]
srtd = lst.sort {|x,y| x[0] <=> y[0] }
=> [[1, "foo"], [2, "qux"], [4, "fbar"]]
like image 31
yan Avatar answered Dec 25 '22 23:12

yan