Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 12 / 68

Recursive Functions

In this lesson you will learn how to write a recursive method in Ruby and understand the basic idea of a function that calls itself. This is for anyone searching for "Ruby recursive function how to use".

A recursive function is a function that calls itself. It suits work that repeats the same calculation pattern, such as "n! = n x (n-1)!". Always provide a stopping condition, or it will call itself forever and the program will crash.

The sample code has factorial keep calling itself as n * factorial(n - 1) until it reaches the stopping condition return 1 if n <= 1. The one-line stopping condition using a trailing if is compact, idiomatic Ruby.

A common stumbling block for beginners is forgetting that stopping condition and recursing forever. Deep recursion also consumes a lot of stack, so it is worth considering whether a loop would do instead.

In real-world development, recursion is a natural fit for hierarchical data such as folder trees or nested comment replies. Understand the mechanism once and you will find it applies widely.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)