Last Updated: February 25, 2016
· mxcl

Ruby `sort_by` Multiple Fields

Ruby’s sort_by is handy, but I needed to sort by multiple parameters, and thought I would have to write my own <=> method on a custom class. But in fact you can do this:

array.sort_by do |item|
  [item.a, item.b]

Not documented, but works great.

3 Responses
Add your response


over 1 year ago ·

There is nothing to document here, it`s just a consequence of Array having <=> defined on it )

over 1 year ago ·