如何将多个块传递给ruby中的方法? [重复]

时间:2022-01-23 10:11:38

This question already has an answer here:

这个问题在这里已有答案:

I can pass multiple parameters and at last one block parameter to method. But it shows error when i try to pass more than one block. I want to know how it can be done?

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

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

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

But below definition gives error

但是低于定义会给出错误

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

1 个解决方案

#1


12  

You can use Proc:

你可以使用Proc:

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

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

#1


12  

You can use Proc:

你可以使用Proc:

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

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