Tail Recursion

A recursive function is said to be tail recursive when the recursive call is the last thing executed by the function.

This is in contrast with classic recursion where each and every function call must be executed to completion in order to get the correct value.

def fibonacci(n, tail1=1, tail2=1)
  if n == 1
    tail1
  elsif n == 2
    tail2
  else
    fibonacci(n - 1, tail2, tail2 + tail1)
  end
end

This solution is much faster than a non-tail recursion.

Sources: