Last active
September 10, 2016 22:01
-
-
Save bil-bas/3753240 to your computer and use it in GitHub Desktop.
Fibonacci sequence - using infinite enumerator in Ruby.
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
# Enumerable Fibonacci sequence | |
module Fibonacci | |
class << self | |
include Enumerable | |
def [](index) | |
raise "index must be >= 0" unless index >= 0 | |
raise "index must be an Integer" unless index.is_a? Integer | |
find.with_index {|n, i| i == index } | |
end | |
def each(&block) | |
if block_given? | |
# First two positions are already defined. | |
yield 0 | |
yield 1 | |
@penultimate = 0 | |
@ultimate = 1 | |
# indices for 2...length | |
loop do | |
# Append the sum of the last two numbers and | |
# forget the first of the stored numbers. | |
@penultimate, @ultimate = @ultimate, @penultimate + @ultimate | |
yield @ultimate | |
end | |
else | |
enum_for :each | |
end | |
end | |
end | |
end | |
p Fibonacci.take(0) #=> [] | |
p Fibonacci.take(1) #=> [0] | |
p Fibonacci.take(2) #=> [0, 1] | |
p Fibonacci.take(3) #=> [0, 1, 1] | |
p Fibonacci.take(15) #=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] | |
puts | |
puts "15th value is #{Fibonacci[14]}" #=> 377 | |
puts | |
# Used as an infinite sequence, where we don't know how many we want. | |
puts "All values <= 1000" | |
p Fibonacci.take_while {|i| i < 1000 } | |
#=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment