Ruby sort by multiple values?

后端 未结 7 960
南旧
南旧 2020-12-07 22:05

I have an array of hashes:

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

I want to sort the array first

7条回答
  •  臣服心动
    2020-12-07 22:33

    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}] 
    

提交回复
热议问题