Recursion in Ruby

Ruby supports recursive functions. Here’s a classic example.

# This fact function calls itself until it reaches the
# base case of fact(0).
def fact(n)
  if n == 0
    1
  else
    n * fact(n - 1)
  end
end

puts fact(7)

# Lambdas can also be recursive, but this requires the
# lambda to be assigned to a variable before it's defined.
fib = lambda do |n|
  if n < 2
    n
  else
    # Since fib was previously declared, Ruby
    # knows which function to call with fib here.
    fib.call(n - 1) + fib.call(n - 2)
  end
end

puts fib.call(7)

When you run this program, you’ll see:

$ ruby recursion.rb
5040
13

In this Ruby version:

  1. We define the fact function using Ruby’s def keyword. The function works the same way as in the original example, calling itself recursively until it reaches the base case.

  2. For the Fibonacci sequence, we use a lambda (which is similar to a Proc in Ruby) instead of a closure. In Ruby, lambdas can be recursive without any special declaration.

  3. We use lambda to create the recursive function and assign it to the variable fib.

  4. To call the lambda, we use the call method or the shorthand [] syntax.

  5. The puts function is used to print the results, which is equivalent to fmt.Println in the original example.

This example demonstrates how Ruby handles recursion both in regular methods and in lambdas, which are Ruby’s equivalent to anonymous functions or closures in other languages.