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:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy