如何从数组中求平均值?

如果我有一个数组:

[0,4,8,2,5,0,2,6]

平均得到3.375。


当前回答

无需重复数组(例如,非常适合一行程序):

[1, 2, 3, 4].then { |a| a.sum.to_f / a.size }

其他回答

你可以试试下面的方法:

a = [1,2,3,4,5]
# => [1, 2, 3, 4, 5]
(a.sum/a.length).to_f
# => 3.0

我认为最简单的答案是

list.reduce(:+).to_f / list.size

我非常喜欢定义一个mean()方法,这样我的代码更有表现力。

默认情况下我通常会忽略nil,这是我定义的

def mean(arr)
  arr.compact.inject{ |sum, el| sum + el }.to_f / arr.compact.size
end

mean([1, nil, 5])
=> 3.0

如果您想保留nils,只需删除两个.compact。

为了让公众开心,还有另一个解决方案:

a = 0, 4, 8, 2, 5, 0, 2, 6
a.reduce [ 0.0, 0 ] do |(s, c), e| [ s + e, c + 1 ] end.reduce :/
#=> 3.375
a = [0,4,8,2,5,0,2,6]
a.instance_eval { reduce(:+) / size.to_f } #=> 3.375

不使用instance_eval的版本如下:

a = [0,4,8,2,5,0,2,6]
a.reduce(:+) / a.size.to_f #=> 3.375