在Ruby中将多个代码块作为参数传递 [英] Passing multiple code blocks as arguments in Ruby

查看:160
本文介绍了在Ruby中将多个代码块作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method which takes a code block.

def opportunity
  @opportunities += 1
  if yield
    @performances +=1
  end
end

我这样称呼它:

opportunity { @some_array.empty? }

但是如何将其传递给一个以上的代码块,以便可以两次使用yield,就像这样:

But how do I pass it more than one code block so that I could use yield twice, something like this:

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

和:

opportunity {@some_other_array.empty?} { @some_array.empty? }

我知道这个例子可以在没有屈服的情况下完成,但这只是为了说明.

I am aware that this example could be done without yield, but it's just to illustrate.

推荐答案

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

You can't pass multiple blocks, per se, but you can pass multiple procs or lambdas:

使用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

这篇关于在Ruby中将多个代码块作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆