Ruby如何对散列哈希进行排序?

时间:2011-08-04 14:27:46

标签: ruby-on-rails ruby

我有深沉的哈希哈希:

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

我想排序:solution_ *哈希下:category_ *哈希按键:顺序。有什么建议吗?

(固定)

2 个答案:

答案 0 :(得分:4)

假设您有以下人员的年龄:

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

使用sort_by来获取我们想去的地方:

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

答案 1 :(得分:3)

好的,你没有指明你的问题,所以我假设你想要删除一个图层。我稍微更改了起始哈希,以实际查看排序是否有效:

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}}

编辑:

考虑到您的澄清(并且仍然从我上面发布的修改后的未分类哈希开始):

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}}}