DEV Community

Discussion on: Let's Get Clever #1: Fibonacci Sequence

Collapse
 
oinak profile image
Oinak

Ruby hashes (a.k.a dictionaries) accept a block to calculate missing entries.

You can abuse this mechanism and store only 0 and 1, and then use the default_proc for everything else:

fib = Hash.new do |hash, key|
  hash[key] = hash[key - 1] + hash[key - 2]
end.merge({ 0 => 0, 1 => 1})

(0..10).each do |n|
  puts fib[n]
end
# 0
# 1
# 1
# 2
# 3
# 5
# 8
# 13
# 21
# 34
# 55
# => 1..10