Sort hash by key, return hash in Ruby

前端 未结 10 1453
时光取名叫无心
时光取名叫无心 2020-11-27 10:05

Would this be the best way to sort a hash and return Hash object (instead of Array):

h = {\"a\"=>1, \"c\"=>3, \"b\"=>2, \"d\"=>4}
# => {\"a\"=         


        
10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 10:29

    @ordered = {}
    @unordered.keys.sort.each do |key|
      @ordered[key] = @unordered[key]
    end
    

提交回复
热议问题