How to sort a Ruby Hash alphabetically by keys

前端 未结 5 1388
长发绾君心
长发绾君心 2021-02-05 05:32

I am trying to sort a Hash alphabetically by key, but I can\'t seem to find a way to do it without creating my own Sorting class. I found the code below to sort by value if it\'

5条回答
  •  盖世英雄少女心
    2021-02-05 06:05

    You can create a new empty hash to hold the sorted hash data. Iterate through the returned array and load the data into the new hash to hold the sorted hash data.

    temp = {}
    temp["ninjas"]=36
    temp["pirates"]=12
    temp["cheese"]=222 
    temp = temp.sort_by { |key, val| key }
    
    temp_sorted = {}
    temp.each { |sub_arr| temp_sorted[sub_arr[0]] = sub_arr[1] } 
    temp = temp_sorted
    

    temp now equals {"cheese"=>222, "ninjas"=>36, "pirates"=>12}

提交回复
热议问题