编辑**
arr = [{"番茄" => 2},{"香蕉" => 3},{"牛奶" => 1},{& #34; egg" => 1},{"烹饪箔" => 1},{" apple" => 4},{" apple =→6}]
如何更改值{"apple" => 10}
?
如何定义函数,例如add
以在添加相同密钥时更新值?
例如
arr.add{"banana" =>7}
=>
[{"tomato"=>2}, {"banana"=>10}, {"milk"=>"1 gallon"}, {"egg"=>"1 cart"}, {"cooking foil"=>1}, {"apple"=>10}]
答案 0 :(得分:2)
您可以定义一个使用detect来查找给定密钥并对其进行编辑的函数。如果密钥尚未存在,还要添加新条目。类似的东西:
def add(key, val, arr)
a = arr.detect{|a| a[key]}
a ? a[key] = a[key] + val : arr << {key => val}
arr
end
arr = [{"tomato"=>2}, {"banana"=>3}, {"milk"=>"1 gallon"}, {"egg"=>"1 cart"}, {"cooking foil"=>1}, {"apple"=>4}, {"apple" =>6}]
add("apple", 10, arr)
# => [{"tomato"=>2}, {"banana"=>3}, {"milk"=>"1 gallon"}, {"egg"=>"1 cart"}, {"cooking foil"=>1}, {"apple"=>14}, {"apple"=>6}]
add("banana", 6, arr)
# => [{"tomato"=>2}, {"banana"=>9}, {"milk"=>"1 gallon"}, {"egg"=>"1 cart"}, {"cooking foil"=>1}, {"apple"=>14}, {"apple"=>6}]
add("lemon", 3, arr)
# => [{"tomato"=>2}, {"banana"=>9}, {"milk"=>"1 gallon"}, {"egg"=>"1 cart"}, {"cooking foil"=>1}, {"apple"=>14}, {"apple"=>6}, {"lemon"=>3}]
注意:由于您的数组有两个具有相同键的哈希,detect
将仅更改第一个匹配项。如果要替换所有哈希,可以使用find_all。
答案 1 :(得分:0)
我假设所有以"apple"
作为单个密钥的哈希值都将替换为单个哈希{ "apple"=>tot }
,其中tot
是"apple"
的所有值的总和引用的哈希值中的{1}}。我还假设arr
不会被更改,并且返回的数组中{"apple"=>tot}
的位置并不重要。
arr = [{"tomato"=>2}, {"banana"=>3}, {"milk"=>"1 gallon"}, {"egg"=>"1 cart"},
{"cooking foil"=>1}, {"apple"=>4}, {"apple"=>6}]
apples = arr.select { |h| h.keys.include?("apple") }
arr - apples << { "apple"=> apples.reduce(0) { |tot,h| tot + h["apple"] } }
#=> [{"tomato"=>2}, {"banana"=>3}, {"milk"=>"1 gallon"},
# {"egg"=>"1 cart"}, {"cooking foil"=>1}, {"apple"=>10}]
步骤:
提取以"apple"
作为单个键的哈希值(保持arr
不变):
apples = arr.select { |h| h.keys.include?("apple") }
#=> [{"apple"=>4}, {"apple"=>6}]
计算苹果总数:
tot_apples = apples.reduce(0) { |tot,h| tot + h["apple"] }
#=> 10
选择没有arr
作为关键字的"apple"
元素(保持arr
不变):
a = arr - apples
#=> [{"tomato"=>2}, {"banana"=>3}, {"milk"=>"1 gallon"},
# {"egg"=>"1 cart"}, {"cooking foil"=>1}]
最后,将{ "apple"=>tot_apples }
追加到a
:
a << { "apple"=>tot_apples }
#=> [{"tomato"=>2}, {"banana"=>3}, {"milk"=>"1 gallon"},
# {"egg"=>"1 cart"}, {"cooking foil"=>1}, {"apple"=>10}]