在Ruby中作为参数传递多个代码块

在Ruby中作为参数传递多个代码块,ruby,yield,Ruby,Yield,我有一个采用代码块的方法 def opportunity @opportunities += 1 if yield @performances +=1 end end 我这样称呼它: def opportunity if yield_1 @opportunities += 1 end if yield_2 @performances +=1 end end opportunity{@some_array.empty?} 但是我如何传递多个代

我有一个采用代码块的方法

def opportunity
  @opportunities += 1
  if yield
    @performances +=1
  end
end
我这样称呼它:

def opportunity
  if yield_1
    @opportunities += 1
  end
  if yield_2
    @performances +=1
  end
end
opportunity{@some_array.empty?}

但是我如何传递多个代码块,这样我就可以使用yield两次,比如:

def opportunity
  if yield_1
    @opportunities += 1
  end
  if yield_2
    @performances +=1
  end
end
以及:


我知道这个例子可以在没有收益的情况下完成,但它只是为了说明。

您本身不能传递多个块,但您可以传递多个proc或lambda:

使用1.9语法:

opportunity ->{ @some_array.empty? }, ->{ @some_other_array.empty? }
在方法本身中:

def opportunity(lambda1, lambda2)
  if lambda1.()
    @opportunities += 1
  end
  if lambda2.()
    @performances += 1
  end
end

是否以其他方式声明functionsProc.new{}或lambda{}也可以工作。任何响应
调用
的对象都将使用
方法(
一个
别名。调用
?@MrYoshiji YES!请注意,prc。()使用给定的参数调用prc.call()。隐藏“call”是一种语法