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