Stupid Ruby Trick: Using a Hash to generate the Fibonacci Sequence

by gabebw

Via, which is in turn via Nick Quaranto.

The gist pointed out that, with its default values, is good for implementing Fibonacci sequences. So I decided to check:

fib = do |hash,key|
  k = key.to_i
  hash[key] = case k
    when 0 then 0
    when 1 then 1
    else hash[k-1] + hash[k-2]

This recursive (and memoized!) definition means that you can do fib[18] and get back 2584, plus you get the Fibonacci numbers from F0 (fib[0]) to F17 (fib[17]). Recursively defined Hashes are useful auto-memoized structures.