herpderp herpderp - 1 year ago 109
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 Source
a.sort { |a, b| [a['foo'], a['bar']] <=> [b['foo'], b['bar']] }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download