Consider the following function:
def function
return 1, 2
end
How can I set a
equal to 1 and b
equal to 2, assuming a
and b
are variables?
Please don't recommend a=1
and b=2
, the point is to understand how to access what the function has returned.
You can do using a comma:
a, b = function
In fact, function
returns an array of two elements:
def function
return 1,2
end
=> nil
function
=> [1, 2]
And you are desconstructing the array - that is each element from the array goes to one variable.
fun fact: The keyword return
is needed in this example.