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

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)

+4
source share
2 answers

yield is applied to the block passed in the context of the transfer method. In your case, I suppose it depends on which irb method relies ( lib/ruby/2.0.0/irb/workspace.rb:86 evaluate if caller is something to be done).

If you wrap it in a function, it will work because you are changing the method context:

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

Note the absence of a block for do_once.call in the above example: yield is applied to the block passed to do_stuff , and not to the block passed to do_once .

Alternatively, declare the block explicitly to avoid using the lesson as a whole:

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

You can do:

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

Source: https://habr.com/ru/post/1488588/


All Articles