Last Updated: February 25, 2016
·
4.213K
· fousa

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