Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby sort by multiple values?

Tags:

ruby

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?

like image 591
herpderp Avatar asked Nov 30 '10 01:11

herpderp


3 Answers

a.sort { |a, b| [a['foo'], a['bar']] <=> [b['foo'], b['bar']] }
like image 172
dj2 Avatar answered Nov 09 '22 12:11

dj2


It probably means you're missing one of the fields 'foo' or 'bar' in one of your objects.

The comparison is coming down to something like nil <=> 2, which returns nil (instead of -1, 0 or 1) and #sort_by doesn't know how to handle nil.

Try this:

a.sort_by {|h| [ h['foo'].to_i, h['bar'].to_i ]}
like image 30
Will Madden Avatar answered Nov 09 '22 12:11

Will Madden


What you have posted works in Ruby 1.8.7:

ruby-1.8.7-p302 > a = [{'foo'=>99,'bar'=>1},{'foo'=>0,'bar'=>2}]
 => [{"foo"=>99, "bar"=>1}, {"foo"=>0, "bar"=>2}] 

ruby-1.8.7-p302 > a.sort_by{ |h| [h['foo'],h['bar']] }
 => [{"foo"=>0, "bar"=>2}, {"foo"=>99, "bar"=>1}] 

ruby-1.8.7-p302 > a.sort_by{ |h| [h['bar'],h['foo']] }
 => [{"foo"=>99, "bar"=>1}, {"foo"=>0, "bar"=>2}] 
like image 15
Phrogz Avatar answered Nov 09 '22 11:11

Phrogz