Skip to content

Instantly share code, notes, and snippets.

@7even
Created September 3, 2012 14:46
Show Gist options
  • Save 7even/3609821 to your computer and use it in GitHub Desktop.
Save 7even/3609821 to your computer and use it in GitHub Desktop.
Fibonacci sequence via Enumerator
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