Created
September 3, 2012 14:46
-
-
Save 7even/3609821 to your computer and use it in GitHub Desktop.
Fibonacci sequence via Enumerator
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
def fibonacci(numbers_count) | |
sequence = Enumerator.new do |yielder| | |
current_number, next_number = 0, 1 | |
loop do | |
yielder << current_number | |
current_number, next_number = next_number, current_number + next_number | |
end | |
end | |
numbers_count.times.map { sequence.next } | |
end | |
p fibonacci(20) | |
# => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment