Skip to content

Instantly share code, notes, and snippets.

@parrot-studio
Created December 16, 2014 01:51
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 parrot-studio/3f0f7cf7e1f0bdf2c777 to your computer and use it in GitHub Desktop.
Save parrot-studio/3f0f7cf7e1f0bdf2c777 to your computer and use it in GitHub Desktop.
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