繁体   English   中英

Ruby将嵌套键添加到现有哈希

[英]Ruby add a nested key to an existing hash

我被困在一个看起来很简单的问题上。

如果我有一个交易数组[#<payer: "Robert", dollar: 100, cent: 10>]

totals = Hash.new(0)
transactions.each do |t|
  totals[t.payer] += t.dollar
end
totals

上面的代码将返回{"Robert"=>100} 我正在寻找更接近{"Robert" => { dollar: 100 }}

所以我尝试

totals = Hash.new(0)
transactions.each do |t|
  totals[t.payer][:dollar] += t.dollar
end
totals

但这会返回no implicit conversion of Symbol into Integer Error的no implicit conversion of Symbol into Integer 如果我将[:dollar]更改为["dollar"]它将返回no implicit conversion of String into Integerno implicit conversion of String into Integer

我的问题的根源是什么?

您将哈希条目初始化为0 您不能为数字0编制索引。

如果您希望散列中的值成为对象,则应使每个散列条目为新的散列{ dollar: 0 } ,一种方式是:

> totals = Hash.new { |hash, key| hash[key] = { dollar: 0 } }
> totals[:foo][:dollar] += 50
> totals
 => { :foo => { :dollar => 50 } }
> totals[:foo][:dollar] += 50
> totals[:bar][:dollar] += 10
> totals
 => { :foo => { :dollar => 100 }, :bar => { :dollar => 10 } }

暂无
暂无

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

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