How to sort an array of hashes in ruby

前端 未结 5 990
盖世英雄少女心
盖世英雄少女心 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:17

    Simples:

    array_of_hashes.sort_by { |hsh| hsh[:zip] }
    

    Note:

    When using sort_by you need to assign the result to a new variable: array_of_hashes = array_of_hashes.sort_by{} otherwise you can use the "bang" method to modify in place: array_of_hashes.sort_by!{}

提交回复
热议问题