Ruby方法如何发回不同数量的变量?

Sha*_*ide 2 ruby

当使用RestClient图书馆,我可以得到responseGET是这样的:

resource = RestClient::Resource.new some_url
resource.get do |response|
  # Handle response
end
Run Code Online (Sandbox Code Playgroud)

我还可以添加requestresult参数:

resource.get do |response, request, result|
  # Handle response, request, and result
end
Run Code Online (Sandbox Code Playgroud)

Ruby如何返回一个多个这样的值?

pdo*_*obb 5

诀窍在于,当在Ruby中使用块时,您可以简单地传递任何人都会关心使用的所有值.然后,当您创建块时,您可以简单地捕获传递到块中的第一个,两个,......或所有值.这是因为如果所有的块参数(在你的情况response,requestresult)是可选的.

def eat(meal)
  meal.each { |food| yield(food, 99, 100) }
  'delicious!'
end

eat([1, 2, 3]) { puts "Yum!" }
# Output:
Yum!
Yum!
Yum!
=> "delicious!"

eat([1, 2, 3]) { |a| puts "Yum! #{a}" }
# Output:
Yum! 1
Yum! 2
Yum! 3
=> "delicious!"

eat([1, 2, 3]) { |a, b, c| puts "Yum! #{a}, #{b}, #{c}" }
# Output:
Yum! 1, 99, 100
Yum! 2, 99, 100
Yum! 3, 99, 100
=> "delicious!"
Run Code Online (Sandbox Code Playgroud)

注意eat方法不会改变,只是你提供给方法的块.我们只是修改它以接受更多参数(并用它们做一些事情).