Sort array of objects by multiple fields in Ruby
After searching the interwebs, I found a solution to use sort_by
when you need to sort by multiple field.
An example
I have a model Person with 2 fields: first_name and last_name.
I want to sort an array filled with Person models by last_name and than by first_name.
Well, it's not that hard. Just return an array in the sort_by
block with the fields you want to sort in the order you want to sort them.
people.sort_by do |person|
[person.last_name, person.first_name]
end
Written by Jelle Vandebeeck
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#