Sort a collection by multiple attributes
To sort a collection by an attribute:
items.sort_by { |x| x.last_name }
or using this shorthand:
items.sort_by(&:name)
Now if you want to sort by multiple attributes don't resort to the spaceship operator:
items.sort { |x,y| [ x.last_name, x.first_name] <=> [y.last_name, y.first_name] }
Pass in an array of attributes to sort_by:
items.sort_by { |x| [x.last_name, x.first_name] }
Much cleaner and more expressive. Removes the redundant y side of things and gets rid of that spaceship operator!
Also, Ruby 1.9.2 introduced the sort_by! method so you can also replace your sort! methods too.










