.should be_learning

Monday, March 23, 2009

Calculate Standard Deviation in Ruby

I saw some pretty ugly implementations out there and thought I'd make them more succinct using the fantastic inject method. I recognize that this approach requires two 'walks' across the population array, but I think the cleanliness makes up for it.



def mean(population)
population.inject(0.0) {|sum,x| sum+=x } / population.size
end

def variance(population)
mean = mean(population)
population.inject(0.0) {|variance_sum,x| variance_sum += (x - mean)**2 } /population.size
end

def standard_deviation(population)
Math.sqrt(variance(population))
end

>> mean([1, 3, 24, 17, 12, 6, 14])
=> 11.0
>> standard_deviation([1, 3, 24, 17, 12, 6, 14])
=> 7.59699188589047



Please feel free to share your thoughts.

Monday, December 8, 2008

Dumping ActiveRecord objects to yaml

I needed a quick n easy way to move the contents of specified tables (ActiveRecord models) from my production to my development enviro that didn't require a full database backup/restore.  It seems there are a few different plugins/gems to assist with this (like ar_fixtures from nubyonrails), but they seemed like overkill to me. 

Here's a quick snippet to dump the data out to a file for easy transport:

model = User #replace with your model name
f = File.new("/path/to/data/#{model.to_s}.yaml", "w+"); f.puts model.find(:all).to_yaml; f.close

Innagural Post

Hi! This blog is for me to post personal items and record technical feats and failures. 

If you find anything here interesting or useful, please drop me a note letting me know!

Followers