Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Peter Cooperx http://www.petercooper.co.uk/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

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!
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS