到像
这样的散列数组的散列{'1' => [{'a' => 'ss', 'b' => 'tt'},
{'a' => 'sdd', 'b' => 'tdd'}],
'2' => [{'a' => 'ffff', 'b' => 'sds'}],
'3' => [{'a' => 'ddd', 'b' => 'ssss'},
{'a' => 'sss', 'b' => 'sssss'}]}
我想在数组的每个哈希中添加'c' => 'xyz'
来获取
{'1' => [{'a' => 'ss', 'b' => 'tt', 'c' => 'xyz'},
{'a' => 'sdd', 'b' => 'tdd', 'c' => 'xyz'}],
'2' => [{'a' => 'ffff', 'b' => 'sds', 'c' => 'xyz'}],
'3' => [{'a' => 'ddd', 'b' => 'ssss', 'c' => 'xyz'},
{'a' => 'sss', 'b' => 'sssss', 'c' => 'xyz'}]}
我该如何实现?
答案 0 :(得分:1)
my_arrays = {'1' => [{'a' => 'ss', 'b' => 'tt'},
{'a' => 'sdd', 'b' => 'tdd'}],
'2' => [{'a' => 'ffff', 'b' => 'sds'}],
'3' => [{'a' => 'ddd', 'b' => 'ssss'},
{'a' => 'sss', 'b' => 'sssss'}]}
my_arrays.each do |key, value|
value.each do |val|
val.store('c', 'xyz')
end
end
答案 1 :(得分:1)
h = {'1' => [{'a' => 'ss', 'b' => 'tt'},
{'a' => 'sdd', 'b' => 'tdd'}],
'2' => [{'a' => 'ffff', 'b' => 'sds'}],
'3' => [{'a' => 'ddd', 'b' => 'ssss'},
{'a' => 'sss', 'b' => 'sssss'}]}
h.values.each do |ary|
ary.each do |inner_hash|
inner_hash['c'] = 'xyz'
end
end
以上解决方案与marmeladze's answer非常相似,所以让我解释一下差异:
inner_hash['c'] = 'xyz'
使用元素分配语法而不是调用#store
。他们做exactly the same。在评论marmeladze的回答时,你问:
我们可以通过迭代一次而不是每次循环来实现这个吗?
h.values
为我们提供了一个数组数组。 (因为它给出了h
的值数组,h
的值是数组。)我们可以使用flatten
折叠嵌套数组,因此只需一次显式迭代即可实现相同的结果:
h.values.flatten.each do |inner_hash|
inner_hash['c'] = 'xyz'
end
或,(等效地),如果你更喜欢一行
h.values.flatten.each { |ih| ih['c'] = 'xyz' }