Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

Sorting an array of objects in Ruby by object attribute?

General • Asked by SarikaA

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.

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 29,763+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.