You can return multiple values
on a method using comma-separated values when you return the data.
Check the example below
def multiple_values
return 1, 2, 3, 4
end
Here we are creating a method called multiple_values
that return 4 values. Each of them separated by a comma, in this form when we call multiple_values
as a result, we will see an array with all these values. So the first one 1 will be at position 0
of the array, 2 will be at position 1
, 3 will be at position 2
and the last value 4 will be at position 3
of the array.
Let’s call our multiple_values
method
def print_values
values = multiple_values
_1 = values.first
_2 = values[1]
_3 = values[2]
_4 = values[3]
p "first - #{_1}, two - #{_2}, three - #{_3}, four - #{_4}"
# => "first - 1, two - 2, three - 3, four - 4"
end
print_values
Calling the method
We created a method called print_values
that will print the values of the array returned by multiple_values
method.
As you can see we store the array returned by multiple_values
in a variable called values
, this values
now contain all the values that we returned before. So for this example to show clearly what values
contain we created a variable for each value of the array. Variable _1
called a shortcut method of the array to retrieve
the first element of the array even though it will work exactly the same way as values[0]
. Then we have the rest of the variables _2, _3, _4
to store the remaining values.
In the last line of the method, we print with a custom format the variables. So to make this work don’t forget to call print_values
to see what it does.
If you are the kind of person that likes to play with the code. Here is the link of the live version https://repl.it/@ViriCruz/multiplevalues
Feel free to play around with the code.
Top comments (3)
That is a very neat explanation, thanks for sharing!
I see your post is centered on the how and not on the why.
One of the most common errors in ruby is:
NoMethodError: undefined method 'foo' for nil:NilClass
It comes from calling a method on the result of a function that we forgot could return
nil
.Usually, when I feel tempted to return mutiple or complex values, I tend to:
A) Return a hash than documents what they are:
B) Return an object with a NullObject pattern to avoid
nil.something
down the line.I know the example is a bit contrived due to brevity, but I hope it lets my point though.
What do you think?
P.S.: Sandi Metz on this matters
Yes, you're right
NoMethodError: undefined method 'foo' for nil:NilClass
this a very common error in ruby and I understand your point of view. Thanks for sharing your opinions! 😁Thanks, I was looking for how to return a tuple.
Tip - you can unpack all the variables in one line.