【问题标题】:Is it possible to pass more than one block to a method in Ruby?是否可以将多个块传递给 Ruby 中的方法?
【发布时间】:2011-04-03 07:10:19
【问题描述】:

类似:

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

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

【问题讨论】:

标签: ruby block codeblocks


【解决方案1】:

你不能以那种方式传递多个块,但你可以传递多个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>

【讨论】:

  • 好的,我明白了。我想我也可以使用 lambda { puts "bla" }。我想底线是我在方法定义中最多只能使用 &block 一次。谢谢。
【解决方案2】:

Ruby 1.9 中的语法更可爱:

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

【讨论】:

  • 注意这里替换了Mark's answer中的foo(Proc.new {puts 'one'}, Proc.new {puts 'two'}),你仍然需要将函数定义为foo(b1,b2),而不是foo(&b1, &b2)
猜你喜欢
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 2012-06-10
  • 2014-11-26
  • 2019-02-15
  • 2011-01-16
相关资源
最近更新 更多