How to sort an array of hashes in ruby

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

    If you have Nested Hash (Hash inside a hash format) as Array elements (a structure like the following) and want to sort it by key (date here)

    data =  [
        {
            "2018-11-13": {
                "avg_score": 4,
                "avg_duration": 29.24
            }
        },
        {
             "2017-03-13": {
                "avg_score": 4,
                "avg_duration": 40.24
            }
        },
        {
             "2018-03-13": {
                "avg_score": 4,
                "avg_duration": 39.24
            }
        }
    ]
    

    Use Array 'sort_by' method as

    data.sort_by { |element| element.keys.first }
    

提交回复
热议问题