Sorting an array of objects in Ruby by object attribute?

Viewed 95351

I have an array of objects in Ruby on Rails. I want to sort the array by an attribute of the object. Is it possible?

9 Answers

I recommend using sort_by instead:

objects.sort_by {|obj| obj.attribute}

Especially if attribute may be calculated.

Or a more concise approach:

objects.sort_by(&:attribute)

Yes, using Array#sort! this is easy.

myarray.sort! { |a, b|  a.attribute <=> b.attribute }

More elegant objects.sort_by(&:attribute), you can add on a .reverse if you need to switch the order.

Array#sort works well, as posted above:

myarray.sort! { |a, b|  a.attribute <=> b.attribute }

BUT, you need to make sure that the <=> operator is implemented for that attribute. If it's a Ruby native data type, this isn't a problem. Otherwise, write you own implementation that returns -1 if a < b, 0 if they are equal, and 1 if a > b.

Related