Passing multiple code blocks as arguments in Ruby

旧城冷巷雨未停 提交于 2019-12-17 16:05:12

问题


I have a method which takes a code block.

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

and I call it like this:

opportunity { @some_array.empty? }

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

and:

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.


回答1:


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

Using 1.9 syntax:

opportunity ->{ @some_array.empty? }, ->{ @some_other_array.empty? }

and in the method itself:

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


来源:https://stackoverflow.com/questions/2463612/passing-multiple-code-blocks-as-arguments-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!