Generating a Sequence of Numbers
def fibonacci(limit = nil)
seed1 = 0
seed2 = 1
while not limit or seed2 <= limit
yield seed2
seed1, seed2 = seed2, seed1 + seed2
end
end
fibonacci(3) { |x| puts x }
# 1
# 1
# 2
# 3
fibonacci(1) { |x| puts x }
# 1
# 1
fibonacci { |x| break if x > 20; puts x }
# 1
# 1
# 2
# 3
# 5
# 8
# 13
Related examples in the same category