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

Methods That Return Multiple Values

In this lesson you will learn to return several values from a Ruby method using an array, so one call can hand back more than one result. This is for anyone searching for "Ruby return multiple values".

A Ruby method returns several values as an array, as in [a, b], and the caller receives them with a, b = someMethod(...). Picture handing over one box containing two cards, a name and a score.

The sample code has min_max return the array [nums.min, nums.max], and the caller receives it with the multiple assignment smallest, largest = min_max(...). The flexibility of Ruby's multiple assignment, which needs no square brackets on the left, is the key point.

A common stumbling block for beginners is the idea of multiple assignment itself. It lets you spread the elements of an array straight into separate variables, and the same mechanism applies broadly to splitting arrays.

Designing how the return value is received, not just what it is, is what makes a method pleasant to use. For work where several values naturally belong together, such as coordinates or ranges, this form is common in practice.

๐Ÿ“– 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)