Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Created February 26, 2013 20:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jeffreyiacono/5041747 to your computer and use it in GitHub Desktop.
running average generator, written while reading about python generators @ http://excess.org/article/2013/02/itergen2
class RunningAverageGenerator
def initialize seed = []
@sum = seed.reduce(:+) || 0
@count = seed.count || 0
end
def << number
@count += 1
@sum += number
@sum / @count.to_f
end
end
r = RunningAverageGenerator.new
r << 2
# => 2
r << 3
# => 2.5
r << 3
# => 2.6666
r.inspect
# => "#<RunningAverageGenerator:0x007fe41403dd60 @sum=8, @count=3>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment