How to sort an array of hashes in ruby

前端 未结 5 992
盖世英雄少女心
盖世英雄少女心 2020-11-30 19:53

I have an array, each of whose elements is a hash with three key/value pairs:

:phone => \"2130001111\", :zip => \"12345\", :city => \"sometown\"
         


        
5条回答
  •  隐瞒了意图╮
    2020-11-30 20:21

    Use the bang to modify in place the array:

    array_of_hashes.sort_by!(&:zip)
    

    Or re-assign it:

    array_of_hashes = array_of_hashes.sort_by(&:zip)
    

    Note that sort_by method will sort by ascending order.

    If you need to sort with descending order you could do something like this:

    array_of_hashes.sort_by!(&:zip).reverse!
    

    or

    array_of_hashes = array_of_hashes.sort_by(&:zip).reverse
    

提交回复
热议问题