2010-09-16 71 views
36

阵列的价值这是我的数组总和哈希

[{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2 
, :alt_amount=>30}] 

我想导致

[{:amount => 30}] or {:amount = 30} 

任何想法?

回答

47

您可以使用inject来计算所有金额。如果需要,您可以将结果放回散列。

arr = [{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2, :alt_amount=>30}]  
amount = arr.inject(0) {|sum, hash| sum + hash[:amount]} #=> 30 
{:amount => amount} #=> {:amount => 30} 
+0

谢谢@ sepp2k这个非常有用。在上面的答案中,我们必须命名键 - 如果我们想要所有键的总和 - (即我们不想单独命名它们 - 你知道我们将如何解决这个问题吗?) – BKSpurgeon 2017-03-18 00:25:41

8

这是做这件事:

a = {amount:10,gl_acct_id:1,alt_amount:20},{amount:20,gl_acct_id:2,alt_amount:30} 
a.map {|h| h[:amount] }.reduce(:+) 

不过,我得到的是你的对象模型有点欠缺的感觉。有了一个更好的对象模型,你可能能够做这样的事情:

a.map(&:amount).reduce(:+) 

甚至只是

a.sum 

注意,如@ sepp2k指出的那样,如果你想摆脱一个Hash,您需要再次将其包装在Hash中。

+0

@mittag你能告诉我我应该是一个更好的对象模型?所以我可以使用这个... a.map(&:amount).reduce(:+) – 2010-09-16 17:50:04

+2

@krunal:最基本的例子:'Foo = Struct.new(:amount,:gl_acct_id,:alt_amount); a = [Foo.new(10,1,20),Foo.new(20,2,30)]; a.map(&:amount).inject(:+)#=> 30' – sepp2k 2010-09-17 18:34:38

+0

@ sepp2k:谢谢!错过了那一个。 – 2010-09-17 18:36:18

-2
total=0 
arr = [{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2, :alt_amount=>30}] 
arr.each {|x| total=total+x[:amount]} 
puts total 
+0

大致相当于这一行:''total = arr.inject(0){| sum,hash | sum + = hash [:amount]}''' – 2017-12-27 09:45:20

48

array.map { |h| h[:amount] }.sum

+6

应该指出,这是一个轨道延伸... – Rob 2016-05-18 03:41:36

+3

,而使用轨道,可能会更短:array.sum {| h | h [:amount]} – alostr 2016-11-22 16:06:00

2
[{ 
    :amount=>10, 
    :gl_acct_id=>1, 
    :alt_amount=>20 
},{ 
    :amount=>20, 
    :gl_acct_id=>2, 
    :alt_amount=>30 
}].sum { |t| t[:amount] } 
+1

欢迎来到Stack Overflow! __explain__你的答案通常更好,而不仅仅是发布代码。 – 2016-10-24 12:53:31

+0

欢迎来到Stack Overflow!虽然这段代码可能有助于解决这个问题,但它并没有解释_why_和/或_how_它是如何回答这个问题的。提供这种附加背景将显着提高其长期教育价值。请[编辑]您的答案以添加解释,包括适用的限制和假设。 – 2016-10-24 16:28:30