Sorting an array of objects in Ruby by object attribute?

Satyam Gautam picture Satyam Gautam · May 19, 2009 · Viewed 79k times · Source

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?

Answer

Scott picture Scott · May 20, 2009

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)