【发布时间】:2017-01-11 05:50:29
【问题描述】:
我有一个交易数组,其中包含交易哈希。我想遍历交易哈希数组,并为每个财政年度求和利息和本金值。然后需要将这些添加到相应的数组中,按财政年度分组,如下所示。
简而言之:
每个财政年度:
1.对兴趣键的值求和
2.创建哈希
3.将哈希添加到各自的数组中
4.重复主值
我在第一步有点卡住:对于每个财政年度,做 x - 任何帮助将不胜感激。
Ruby 2.3.1
给定
@transactions = [
{"interest" => "120.00", "principal" => "250", "financial_year" => "2017"},
{"interest" => "120.00", "principal" => "250", "financial_year" => "2017"},
{"interest" => "120.00", "principal" => "250", "financial_year" => "2017"},
{"interest" => "120.00", "principal" => "250", "financial_year" => "2018"},
{"interest" => "120.00", "principal" => "250", "financial_year" => "2018"},
{"interest" => "120.00", "principal" => "250", "financial_year" => "2019"},
{"interest" => "120.00", "principal" => "250", "financial_year" => "2019"}
]
我想计算
@interest_totals = [
{"financial_year" => "2017", "total" => "360"}
{"financial_year" => "2018", "total" => "240"}
{"financial_year" => "2019", "total" => "240"}
]
和
@principal_totals = [
{"financial_year" => "2017", "total" => "750"}
{"financial_year" => "2018", "total" => "500"}
{"financial_year" => "2019", "total" => "500"}
]
【问题讨论】:
-
虽然您的印刷引号看起来很漂亮,但您必须在 Ruby 中使用
"..."和'...'而不是“...”和‘...’。 -
我编辑了问题以纠正@Stefan 发现的错误。詹姆斯,请始终运行您的代码(例如在 IRB 中)以确保在发布之前它是正确的。
-
会做@CarySwoveland - 谢谢
标签: ruby-on-rails arrays ruby hash