Last Updated: February 25, 2016
·
1.246K
· jasdeepsingh

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 :) (http://en.wikipedia.org/wiki/Triangular_number)

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