If you are a ruby programmer, you might come across a hash block memoization pattern. For a simple example, I present to you a memorialized version of the Fibonacci sequence:
fib_hash = Hash.new do |h,i| h[i] = h[i-1] + h[i-2] end
Of course, this is not the only way to create a memoized version of the Fibonacci sequence. You can also do the following:
@cache = {}; @cache[1] = 1; @cache[2] = 1 def memo_fib(n) @cache[n] ||= (memo_fib(n-1) + memo_fib(n-2)) end
I hope you see how the hash block memoization pattern maps to the second version, which is much more common in many other languages. I would like to know if there is a difference between the two versions? I can't shake the feeling that the hash block version is more efficient, but I can't really justify why.
source share