求和索引散列的子值

时间:2016-12-23 13:30:40

标签: ruby-on-rails ruby hash

所以我正在开发一个项目,我有一个哈希如下:

{ 1=>{:id=>133, 
     :total=>#<BigDecimal:cc08558,'0.41323E3',18(18)>}, 
  2=>{:id=>134, 
      :total=>#<BigDecimal:cc082b0,'0.523E1',18(18)>}, 
  6=>{:id=>166, 
      :total=>#<BigDecimal:cbdbb98,'0.837E2',18(18)>}, 
  8=>{:id=>168, 
      :total=>#<BigDecimal:cbdb8a0,'0.72236E3',18(18)>}, 
  9=>{:id=>169, 
      :total=>#<BigDecimal:cbdb738,'0.132E3',9(18)>} }

我希望在此哈希中添加元素,该哈希具有哈希中所有总值的总和。结果如下:

{ 1=>{:id=>133, 
     :total=>#<BigDecimal:cc08558,'0.41323E3',18(18)>}, 
  2=>{:id=>134, 
      :total=>#<BigDecimal:cc082b0,'0.523E1',18(18)>}, 
  6=>{:id=>166, 
      :total=>#<BigDecimal:cbdbb98,'0.837E2',18(18)>}, 
  8=>{:id=>168, 
      :total=>#<BigDecimal:cbdb8a0,'0.72236E3',18(18)>}, 
  9=>{:id=>169, 
      :total=>#<BigDecimal:cbdb738,'0.132E3',9(18)>},
  0=>{:id=>000,
      :total=><whatever the total is>} }

但是我在完成这项工作时遇到了一些麻烦:

month_hash.each.sum(:total)

但这似乎没有做我想做的事。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用values获取所有子哈希值,并使用inject迭代哈希值并总计总和:

h

{1=>{:id=>133, :total=>413.23}, 2=>{:id=>134, :total=>5.23}, 6=>{:id=>166, :total=>83.7}, 8=>{:id=>168, :total=>722.36}, 9=>{:id=>169, :total=>132.0}, 0=>{:id=>0, :total=>1356.52}} 现在是:

{1=>{:id=>133, :total=>413.23},
 2=>{:id=>134, :total=>5.23},
 6=>{:id=>166, :total=>83.7},
 8=>{:id=>168, :total=>722.36},
 9=>{:id=>169, :total=>132.0},
 0=>{:id=>0, :total=>2713.04}}

请注意,如果再次运行它,您将添加两次总和:

{{1}}