Skip to content

Instantly share code, notes, and snippets.

@apeiros
Created September 22, 2016 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apeiros/608b1c6a55fbcefbb2ac7a0a0e3db49a to your computer and use it in GitHub Desktop.
Save apeiros/608b1c6a55fbcefbb2ac7a0a0e3db49a to your computer and use it in GitHub Desktop.
module Enumerable
def rolling_average(n)
return enum_for(__method__, n) unless block_given?
enum = each
values = n.times.map { enum.next } # rescue StopIteration
sum = values.inject(:+)
yield sum.quo(n)
loop do
sum -= values.shift
values << enum.next
sum += values.last
yield sum.quo(n)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment