Recursion in Ruby
Ruby supports recursive functions. Here’s a classic example.
When you run this program, you’ll see:
In this Ruby version:
We define the
fact
function using Ruby’sdef
keyword. The function works the same way as in the original example, calling itself recursively until it reaches the base case.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.
We use
lambda
to create the recursive function and assign it to the variablefib
.To call the lambda, we use the
call
method or the shorthand[]
syntax.The
puts
function is used to print the results, which is equivalent tofmt.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.