Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Just do a multiple assignment:

def function
  return 1, 2
end

a, b = function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top