Ruby Recursion and Memoization
A method can call itself. Memoise results in a hash to avoid repeating work.
Example
def fib(n, memo = {})
return n if n < 2
memo[n] ||= fib(n - 1, memo) + fib(n - 2, memo)
end
puts fib(50)
def fact(n) = n <= 1 ? 1 : n * fact(n - 1)
puts fact(10)Result
12586269025 3628800
Exercise
Call the method itself.
def fact(n) = n <= 1 ? 1 : n * (n - 1)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.