如何将多个块传递给ruby中的方法?

时间:2012-02-25 14:37:21

标签: ruby closures

我可以将多个参数和最后一个块参数传递给方法。但是当我尝试传递多个块时它会显示错误。我想知道怎么做?

def abc(x, &a)
  x.times { a.call("hello") }
end

abc(3) {|a| puts "#{a} Sana"}
abc(1, &proc{|a| puts "#{a} Sana"})

但是下面的定义会给出错误

def xyz(x, &a, &b)
  puts x
  a.call
  b.call
end

1 个答案:

答案 0 :(得分:12)

您可以使用Proc

def xyz(x, a, &b)
  puts x
  a.call
  b.call
end

xyz(3, Proc.new { puts 'foo' }) { puts 'bar' }

# or simpler

xyz(3, proc { puts 'foo' }) { puts 'bar' }