-
-
Save apeiros/608b1c6a55fbcefbb2ac7a0a0e3db49a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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