开发者

Ruby how to sort hash of hashes?

I have that deep Hash of hashes:

my_hash = { 
    :category_1 => {
        :solution_1 => { :order => 1 },
   开发者_运维百科     :solution_2 => { :order => 2 }
    },
    :category_2 => {
        :solution_3 => { :order => 3 },
        :solution_4 => { :order => 4 }  
    }
}

I want to sort :solution_* hashes under :category_* hashes by key :order. Any suggestions?

(fixed)


Let's say you have the following hash of people to ages:

people = {
  :fred => { :name => "Fred", :age => 23 },
  :joan => { :name => "Joan", :age => 18 },
  :pete => { :name => "Pete", :age => 54 }
}

use sort_by to get where we want to go:

people.sort_by { |k, v| v[:age] }
  # => [[:joan, {:name=>"Joan", :age=>18}], 
        [:fred, {:name=>"Fred", :age=>23}],
        [:pete, {:name=>"Pete", :age=>54}]]


Ok, you didn't specify your question, so I'm assuming you want one layer removed. I changed the starting hash a bit to actually see if the sorting works:

my_hash = { 
    :category_1 => {
        :solution_1 => { :order => 2 },
        :solution_2 => { :order => 3 }
    },
    :category_2 => {
        :solution_3 => { :order => 4 },
        :solution_4 => { :order => 1 }  
    }
}

Hash[my_hash.inject({}) { |h, (k, v)| h.merge(v) }.sort_by { |k,v| v[:order] }]
#=> {:solution_4=>{:order=>1}, :solution_1=>{:order=>2}, :solution_2=>{:order=>3}, :solution_3=>{:order=>4}}

EDIT:

Taking into account your clarification (and still starting from the modified unsorted hash I posted above):

sorted = my_hash.inject({}) do |h, (k, v)| 
  h[k] = Hash[v.sort_by { |k1, v1| v1[:order] }] 
  h 
end
#=> {:category_1=>{:solution_1=>{:order=>2}, :solution_2=>{:order=>3}}, :category_2=>{:solution_4=>{:order=>1}, :solution_3=>{:order=>4}}}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜