Ruby sort by multiple values?

后端 未结 7 956
南旧
南旧 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:14

    This error appeares when you have unstable keys and trying to sort by 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 it doesnt work for me in

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

    where digit is unstable

提交回复
热议问题