herpderp herpderp - 4 months ago 17
Ruby Question

Ruby sort by multiple values?

I have an array of hashes:

a=[{ 'foo'=>0,'bar'=>1 },
{ 'foo'=>0,'bar'=>2 },
... ]


I want to sort the array first by each hash's 'foo', then by 'bar'. Google tells me this is how it's done:

a.sort_by {|h| [ h['foo'],h['bar'] ]}


But this gives me the ArgumentError "comparison of Array with Array failed". What does this mean?

dj2 dj2
Answer
a.sort { |a, b| [a['foo'], a['bar']] <=> [b['foo'], b['bar']] }
Comments