简体   繁体   English

是否可以将多个块传递给Ruby中的方法?

[英]Is it possible to pass more than one block to a method in Ruby?

Something like: 就像是:

def foo(&b1, &b2)
  b1.call
  b2.call
end

foo() { puts "one" } { puts "two" }

You can't pass multiple blocks in that way, but you can pass multiple proc or lambda objects: 您不能以这种方式传递多个块,但您可以传递多个proclambda对象:

irb(main):005:0> def foo(b1, b2)
irb(main):006:1>   b1.call
irb(main):007:1>   b2.call
irb(main):008:1> end
=> nil
irb(main):009:0> foo(Proc.new {puts 'one'}, Proc.new {puts 'two'})
one
two
=> nil
irb(main):010:0>

语法在Ruby 1.9中很可爱:

foo ->{puts :one}, ->{puts :two}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM