简体   繁体   English

Ruby如何排序散列的哈希?

[英]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. 我想通过键:order在:category_ *哈希下对:solution_ *哈希排序。 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: 使用sort_by获取我们要去的地方:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM