Ruby sort by multiple values?

后端 未结 7 924
南旧
南旧 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:29

    consider compacting the array (removing nil entries), and as a bonus, if it's string comparision, downcase the values for case insensitive sorting.

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

提交回复
热议问题