randomizing an array in ruby (the right way)
# be sure to use sort_by rather than sort quiz = (1..10).to_a quiz.sort_by { rand }
12382 users tagging and storing useful source code snippets
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
# be sure to use sort_by rather than sort quiz = (1..10).to_a quiz.sort_by { rand }
class Array; def sum; inject( nil ) { |sum,x| sum ? sum+x : x }; end; end
[1,2,3].sum # => 6 ['a','b','c'].sum # => 'abc' [['a'], ['b','c']].sum # => ['a', 'b', 'c']
class Array; def mean; sum / size; end; end
[1,2,1000].mean # => 334
function maybe_unserialize ( $original ) { if ( false !== $gm = @ unserialize($original) ) return $gm; else return $original; }
class Array def swap!(a,b) self[a], self[b] = self[b], self[a] self end end
[1,2,3,4].swap!(2,3) # = [1,2,4,3] etc..