Skip to content

Instantly share code, notes, and snippets.

@timmatheson
Created October 16, 2010 04:03
Show Gist options
  • Save timmatheson/629394 to your computer and use it in GitHub Desktop.
Save timmatheson/629394 to your computer and use it in GitHub Desktop.
Moving Averages for the Ruby Array Class
# Examples
# [1,1,2,1,1,2,2].moving_average(2) => [1, 1, 1, 2]
class Array
# Calculates the moving average
# given a Integer as a increment period
def moving_average(increment = 1)
return self.average if increment == 1
a = self.dup
result = []
while(!a.empty?)
data = a.slice!(0,increment)
result << data.average
end
result
end
# Calculates the average
def average
(self.sum/self.size)
end
end
@booch
Copy link

booch commented Mar 31, 2016

You need to add Array#sum as well:

class Array
  def sum
    inject(0){|sum,x| sum + x }
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment