ruby block and returning something from block

后端 未结 4 1090
没有蜡笔的小新
没有蜡笔的小新 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:14

    The {} block includes the context in which it is given, so the return tries to return from the line lab { return 10; }. You can actually make this work (sometimes even in a useful manner) by placing that line inside a method, which will then return (i.e. "after" is not printed).

    To return the 10 to block.call, omit the return (or substitute next).

提交回复
热议问题