如何从数组数组中添加数量

时间:2016-10-07 21:22:09

标签: arrays ruby

我有一个像这样的数组......

a1 = [[9, -1811.4], [8, 959.86], [7, -385], [6, -1731.39], [5, 806.78], [4, 2191.65]]

我需要从总数组中得到第二项(金额)的平均值。

所以加-1811.4,959.86,-385,-1731.39,806.78除以计数(6)

我试过......

a1.inject{ |month, amount| amount }.to_f / a1.size

这是不对的,我无法看到我需要做什么

2 个答案:

答案 0 :(得分:3)

a1.map(&:last).inject(:+) / a1.size.to_f
#=> 5.0833333333332575

步骤:

# 1. select last elements
a1.map(&:last)
#=> [-1811.4, 959.86, -385, -1731.39, 806.78, 2191.65]
# 2. sum them up
a1.map(&:last).inject(:+)
#=> 30.499999999999545
# 3. divide by the size of a1
a1.map(&:last).inject(:+) / a1.size.to_f
#5.0833333333332575

答案 1 :(得分:2)

通过a1一次就足够了。

a1.reduce(0) { |tot, (_,b)| tot + b }/a1.size.to_f
  #=> 5.0833333333332575

.to_f允许a1仅包含整数值。

步骤:

tot = a1.reduce(0) { |tot, (_,b)| tot + b }
  #=> 30.499999999999545 
n = a1.size.to_f
  #=> 6.0 
tot/n
  #=> 5.0833333333332575