如何根据属性值将事物放入哈希数组中?

时间:2017-03-14 19:11:50

标签: arrays ruby hash

我试图将这些tools放入此数组中的右侧组哈希对象中。我不确定如何用Ruby做到这一点。

groups = [
  { group: 'Business Training', tools: [] },
  { group: 'Human Resources', tools: [] },
  { group: 'Clean', tools: [] },
  { group: 'Example', tools: [] }
]

tools = [
  { name: "Foo", group: "Clean", id: 1 },
  { name: "Bar", group: "Clean", id: 2 },
  { name: "Baz", group: "Business Training", id: 3 },
]

我想结束这样的结构:

groups = [
  { 
    group: 'Business Training', 
    tools: [
      { name: "Baz", group: "Business Training", id: 3 },
    ] 
  },
  { group: 'Human Resources', tools: [] },
  { 
    group: 'Clean', 
    tools: [
      { name: "Foo", group: "Clean", id: 1 },
      { name: "Bar", group: "Clean", id: 2 },
    ] 
  },
  { group: 'Example', tools: [] }
]

4 个答案:

答案 0 :(得分:1)

tools.each do |tool|
  group = groups.find { |item| item[:group] == tool[:group] }
  group[:tools] << tool
end

答案 1 :(得分:0)

result = groups.map do |group|
  {
    group: group[:group],
    tools: tools.select do |tool|
      tool[:group] == group[:group]
    end
  }
end
puts result

打印哪些:

{:group=>"Business Training", :tools=>[{:name=>"Baz", :group=>"Business Training", :id=>3}]}
{:group=>"Human Resources", :tools=>[]}
{:group=>"Clean", :tools=>[{:name=>"Foo", :group=>"Clean", :id=>1}, {:name=>"Bar", :group=>"Clean", :id=>2}]}
{:group=>"Example", :tools=>[]}

答案 2 :(得分:0)

还有一个解决方案:

groups.each do |group|
   group[:tools] = 
      tools.select { |tool| tool[:group] == group[:group] }
end

答案 3 :(得分:0)

h = tools.each_with_object({}) { |g,h| h[g[:group]] = g }
  #=> { "Clean"            =>{:name=>"Bar", :group=>"Clean", :id=>2},
  #     "Business Training"=>{:name=>"Baz", :group=>"Business Training", :id=>3}} 
groups.map { |g| g.update(tools: h[g[:group]]) }
  #=> [{:group=>"Business Training",
  #     :tools=>{:name=>"Baz", :group=>"Business Training", :id=>3}},
  #    {:group=>"Human Resources",
  #     :tools=>nil},
  #    {:group=>"Clean",
  #     :tools=>{:name=>"Bar", :group=>"Clean", :id=>2}},
  #    {:group=>"Example",
  #     :tools=>nil}] 

构建哈希h只需要通过tools一次。对于groups的每个元素,这允许简单的哈希值替换,这比为tools的每个元素搜索groups的方法更快,反之亦然。

请注意,除了变异groups之外,还会返回更新后的值。如果您不希望使用Hash#update修改groups替换Hash#merge(又名merge!)。