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 of "foo", then by "bar". Google tells me how to do this:

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

But that gives me the ArgumentError argument "Comparing an array with an array." What does it mean?

+60
ruby
Nov 30 '10 at 1:18
source share
6 answers
 a.sort { |a, b| [a['foo'], a['bar']] <=> [b['foo'], b['bar']] } 
+63
Nov 30 '10 at 1:22
source share

You probably lost one of the "foo" or "bar" fields in one of your objects.

The comparison comes down to something like nil <=> 2 , which returns nil (instead of -1 , 0 or 1 ) and #sort_by does not know how to handle nil .

Try the following:

 a.sort_by {|h| [ h['foo'].to_i, h['bar'].to_i ]} 
+17
Mar 06 '14 at 20:59
source share

What did you publish 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}] 
+12
Nov 30 '10 at 4:33
source share

This exception occurs when the result array used for comparison contains nil and non-nil values.

+2
Jul 21 '16 at 19:17
source share

This error appears when you have unstable keys and tries to sort them. Example:

 [{'foo'=>99,'bar'=>1},{'foo'=>0,'bar'=>2, 'qwe' => 7}] a.sort_by{|v| v['qwe']} ArgumentError: comparison of NilClass with 7 failed 

Try to do

 a.sort_by{|v| [v['qwe']].select{|k| not k.nil?}} 

But this does not work for me in

 [v['index'],v['count'],v['digit'],v['value']] 

where the figure is unstable

0
Jul 01 '15 at 11:06
source share

Failed to compare Array with Array

This means (at least in my case) that the types of elements in the array are different. When I made sure that all elements of the array have the same time (e.g. Integer ), sorting started to work.

0
Dec 20 '18 at 7:52
source share



All Articles