Taking Mean : Utility Method « Method « Ruby






Taking Mean


def mean(array)
  array.inject(0) { |sum, x| sum += x } / array.size.to_f
end

puts mean([1,2,3,4])                                  # => 2.5
puts mean([100,100,100,100.1])                        # => 100.025
puts mean([-100, 100])                                # => 0.0
puts mean([3,3,3,3])                                  # => 3.0

 








Related examples in the same category

1.Track Median
2.Track Mode
3.mean without float conversion
4.mean and standard deviation
5.Converting Between Degrees and Radians