Ruby sort by multiple values?

后端 未结 7 922
南旧
南旧 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

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

提交回复
热议问题