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-2 of 2 total  RSS 

Generic 'sum' and 'mean' methods for Ruby arrays

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!

Swap elements of an array in Ruby

class Array
    def swap!(a,b)
         self[a], self[b] = self[b], self[a]
    self
    end
end


You can now do stuff like..

[1,2,3,4].swap!(2,3)  # = [1,2,4,3] etc..


Many thanks to Sam Stephenson and technoweenie for their suggestions.
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS