Created
December 16, 2014 01:51
-
-
Save parrot-studio/3f0f7cf7e1f0bdf2c777 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
class Fibonacci | |
class << self | |
include Enumerable | |
def each | |
(1..Float::INFINITY).lazy.each do |i| | |
yield fib(i) | |
end | |
end | |
private | |
def fib(i) | |
return if i < 1 | |
@fib ||= {1 => 0, 2 => 1} | |
return @fib[i] if @fib[i] | |
@fib[i] = @fib[i-1] + @fib[i-2] | |
@fib[i] | |
end | |
end | |
end | |
# Fibonacci.take(10) | |
# => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment