Generic 'sum' and 'mean' methods for Ruby arrays
1 class Array; def sum; inject( nil ) { |sum,x| sum ? sum+x : x }; end; end
It's class agnostic, so you can do this:
1 [1,2,3].sum # => 6 2 ['a','b','c'].sum # => 'abc' 3 [['a'], ['b','c']].sum # => ['a', 'b', 'c']
You can then add a 'mean' operator easily:
1 class Array; def mean; sum / size; end; end
mean only works for numbers though, of course, like so:
1 [1,2,1000].mean # => 334
That said, if your class implements division, it'll also work!