ruby block and returning something from block

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

    return inside a block will return from the method the block is in, not from the block. To return from the block use next (it's named that way because with iterator-methods like each and map returning from the block basically means jumping to the next iteration of the loop).

    Note that when the return value is the last evaluated expression in the block, you don't need any kind of return statement at all, i.e. lab { 10 } will do the same thing.

提交回复
热议问题