我试图将这些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: [] }
]
答案 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!
)。