Return Values
Learn about how and what a method returns.
We'll cover the following
In Ruby, a method always returns exactly one thing (an object), though the returned object can be anything.
The object returned could be the object nil
, meaning nothing. On the other hand, to return a bunch of things at once, we could return an array that holds the things we’re interested in, but the array itself is just one object.
Remember: Every method always returns exactly one object.
No return statement
Also note that we don’t have to use the return
statement, as we do in other languages. In fact, most Ruby code doesn’t use the return
keyword at all.
This is convenient, but it’s also something we need to learn.
If we don’t put in a return
statement inside a method, it still returns an object. Whenever the method is executed, it returns the object produced from the last evaluated statement of the method body.
This is important to understand, so we review it again: if we don’t return anything explicitly, then a method still returns the return value of the last evaluated statement.
Let’s look at our previous example:
def add_two(number)number + 2endp add_two(3)
The last evaluated statement is the expression number + 2
. Because number
is assigned 3
in our example, this expression returns the number 5
, and that’s why the value returned by our method is also 5
.
Sometimes, we want to return from the method early. We can do this using the return
statement. For now, however, we don’t need to worry about this case.