Julio
Julio

Reputation: 6368

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.

Upvotes: 4

Views: 4310

Answers (4)

Peter
Peter

Reputation: 132237

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

lst.sort_by &:first

Upvotes: 9

the Tin Man
the Tin Man

Reputation: 160551

When sorting objects and complex structures use sort_by. Sort_by performs a "Schwartzian Transform" which can make a major difference in sort speed.

Because you didn't provide enough information to be usable I'll recommend you read the docs linked above. You'll find its very easy to implement and can make a big difference.

Upvotes: 1

sawa
sawa

Reputation: 168101

Assuming that you want to sort only according to the first element,

[[1, ..bunch of other stuff],[5, ""],[12, ""],[3, ""],].
sort_by{|n, *args| n}

or

[[1, ..bunch of other stuff],[5, ""],[12, ""],[3, ""],].
sort_by{|n, args| n}

Upvotes: 1

yan
yan

Reputation: 20982

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"]]

Upvotes: 3

Related Questions