Ruby block and returning something from the block

I am using ruby ​​1.8.7.

p = lambda { return 10;}
def lab(block)
  puts 'before'
  puts block.call
  puts 'after'
end
lab p

The code above is displayed

before
10
after

I reorganized the same code into this

def lab(&block)
  puts 'before'
  puts block.call
  puts 'after'
end
lab { return 10; }

Now I get LocalJumpError: unexpected return.

Both codes do the same for me. Yes, in the first case, I pass proc, and in the second case, I pass the block. But the block will convert the block to proc. Therefore, proc.call should behave the same.

And yes, I saw this post Using 'return' in a Ruby Block

+5
source share
4 answers

&, proc. , proc (lambda proc), , .

, :

p = Proc.new { return 10;}
def lab(block)
  puts 'before'
  puts block.call
  puts 'after'
end
lab p

LocalJumpError.

: proc , . , lab, proc , . , , .

Ruby , :

Procs lambdas ,

, . , , , return , .

+8

return , , . next ( , -, each map, , ).

, , - , .. lab { 10 } .

+5

{} , , return lab { return 10; }. ( ), , (.. "" ).

To return 10to block.call, lower return(or replace next).

0
source

I think you just need to dereference the block before passing it:

 foo = lambda { return 10 }

 def trace_block(&fn)
   puts 'before calling fn'
   puts fn.call
   puts 'after caling fn'
 end

 trace_block(&foo)

Output:

  before calling fn
  10
  after caling fn

Additional Information:

0
source

All Articles