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

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

randomizing an array in ruby (the right way)

Snagged from http://www.rubyquiz.com/quiz113.html

# be sure to use sort_by rather than sort
quiz = (1..10).to_a
quiz.sort_by { rand }

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!

Maybe UnSerialize

Checks to see if a string is actually the serialized version of an array. If it is, we return an unserialized version. If not, return the original string. This way, we can just call our function on stored DB values and not worry about checking the results.

This was snagged from the Wordpress 2.0 source. Yayyy for Open Source!

	function maybe_unserialize ( $original ) {
		if ( false !== $gm = @ unserialize($original) )
			return $gm;
		else
			return $original;
	}

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