Easy Memoization with Ruby

Ruby let’s you form Hashes that makes it easier to work with Sequences using memoization. The computations are fast since it’s very much like a function but Memoized inside a hash collection.

Having the sequence available inside a Hash collection gives you more flexibility on how you can work with the sequence. Here’s a quick example to demonstrate this:

Since, everyone does Fibonacci Sequence, We’ll be looking at Triangular Numbers Sequence here:

>> tri = Hash.new { |hash,n| hash[n] = (n*(n+1))/2 }
>> tri[1] = 1 # Setup the base case
>> tri[4]
>> tri[433]