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:
default_proc
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
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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: