herpderp herpderp - 6 months ago 41
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
a.sort { |a, b| [a['foo'], a['bar']] <=> [b['foo'], b['bar']] }