ruby block and returning something from block

后端 未结 4 1094
没有蜡笔的小新
没有蜡笔的小新 2021-02-09 23:30

I am using ruby 1.8.7.

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

Above code output

4条回答
  •  天涯浪人
    2021-02-10 00:04

    When you pass in the block with &, you're converting it to a proc. The important point is that a proc and a lambda are different (lambda is actually a subclass of proc), specifically in how they deal with return.

    So your refactored code is actually the equivalent of:

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

    which also generates a LocalJumpError.

    Here's why: A proc's return returns from its lexical scope, but a lambda returns to its execution scope. So whereas the lambda returns to lab, the proc passed into it returns to the outer scope in which it was declared. The local jump error means it has nowhere to go, because there's no enclosing function.

    The Ruby Programming Language says it best:

    Procs have block-like behavior and lambdas have method-like behavior

    You just have to keep track of what you're using where. As others have suggested, all you need to do is drop the return from your block, and things will work as intended.

提交回复
热议问题