Ask A Question


You’re not receiving notifications from this thread.

Sorting an array of objects in Ruby by object attribute?

SarikaA asked in General

Hi guys,

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?


If the attribute is exposed via a method (as it would be in the common case for Rails models) then this is how many of us would do it:

my_array.sort_by { |item| item.attribute }

or as shorthand for the same:

my_array.sort_by(&:attribute)   #=> [...sorted array...]

However, if you'd rather that objects knew how to sort themselves, therefore giving them the latitude to vary later, then you can push the sort method down into the object, thus:

class MyModel
  def attribute_sort(b)
    self.attribute <=> b.attribute

# and then ...
my_array.sort(&:attribute_sort)  #=> [...sorted array...]

Although arguably more object-oriented, this may be slower if attribute is actually an expensively computed value, due to repeated re-computation of the sorting key.

Note that if your array is actually an ActiveRecord relation then you may be much better off using the order predicate to push the work into the database, especially if the result set is large:


and see


I recommend using sort_by instead:

objects.sort_by {|obj| obj.attribute}

Especially if attribute may be calculated.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,329+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.