xmip3w
Last Updated: February 25, 2016
·
1.499K
· mxcl
Img 0719

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]
end

Not documented, but works great.

Say Thanks
Respond

3 Responses
Add your response

9093

interesting

over 1 year ago ·
9209
Fb9c5f479cc50df9808dbfe582d5d6bd
over 1 year ago ·
9223
6b67518d6700874714698702879014a2

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

over 1 year ago ·