All threads / Sorting an array of objects in Ruby by object attribute?

Ask A Question

Notifications

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
  end
end

# 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:

my_relation.order(:attribute)

and see https://guides.rubyonrails.org/active_record_querying.html#ordering.

I recommend using sort_by instead:

objects.sort_by {|obj| obj.attribute}

Especially if attribute may be calculated.

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.