liveBook · Manning

Recursion

As explained in The Well-Grounded Rubyist, Fourth Edition

Recursion is a programming technique in which a routine invokes itself, directly or indirectly, to solve a problem through progressively smaller or simpler subproblems.

Recursion is a technique in which a function or method calls itself before returning. Each call receives a new local scope, while self can remain the same object. section 5.2.3 section 16.4

A recursive routine needs a terminal clause that returns a result instead of making another call. Without one, the routine continues indefinitely. Recursive calls can progressively reduce their arguments, as in Fibonacci numbers or the sum of squares. section 16.4

Separate local scopes during recursion

A method can call itself with a different argument without changing the caller's local variable. In C#x, the recursive call prints "Second value for a", then the original call resumes and prints "First value for a"; both calls retain the same self.

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains terminal clauses, argument reduction, and per-call local scope, while deferring a full treatment of recursion.
Examples
Demonstrates recursive method scope, Fibonacci evaluation, pattern-matching Fibonacci, and recursively computed sums of squares.
What you can do after
Apply via Ruby by writing recursive Fibonacci and sum-of-squares functions with explicit terminal clauses.
How it connects
Connects recursion with functional programming, Fibonacci sequences, pattern matching, local scope, self, and tail-call optimization.

Also explained in

Compare how 23 books explain recursion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.