Sorting an array of objects in Ruby by object attribute?
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.