Why can't I pass a block to the proc in Ruby?

China☆狼群 提交于 2019-12-07 07:08:35

问题


Why can't I do something like this:

do_once = Proc.new { yield }
do_once.call { puts 1 }

irb throws LocalJumpError: no block given (yield)


回答1:


yield applies to the block passed to the wrapping method context. In your case, I presume it is whichever method irb relies upon (lib/ruby/2.0.0/irb/workspace.rb:86 evaluate, if caller is anything to go by).

If you wrap it in a function it'll work, because you change the method context:

def do_stuff
  do_once = Proc.new { yield }
  do_once.call 
end

do_stuff { puts 1 }

Note the absence of block for do_once.call in the above: yield applies to the block passed to do_stuff, rather than to the block passed to do_once.

Alternatively, declare the block explicitly to avoid the use of yield altogether:

do_once = Proc.new { |&block| block.call }
do_once.call { puts 1 }



回答2:


You can do:

do_once = Proc.new { |&block| block.call }
do_once.call { puts 1 }


来源:https://stackoverflow.com/questions/17353045/why-cant-i-pass-a-block-to-the-proc-in-ruby

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