0

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.

4

2 回答 2

4

您可以使用逗号:

a, b = function

实际上,function返回一个包含两个元素的数组:

def function
  return 1,2
end
=> nil 
function
=> [1, 2] 

而且您正在解构数组 - 即数组中的每个元素都转到一个变量。

有趣的事实:此示例中需要关键字return

于 2013-05-23T19:24:01.307 回答
2

只需做一个多重分配:

def function
  return 1, 2
end

a, b = function
于 2013-05-23T19:24:59.587 回答