ruby block and returning something from block

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

    I think you just need to dereference the block before you pass 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
    

    More info:

    • Understanding Ruby Blocks, Procs and Lambdas
    • Ruby Blocks 101

提交回复
热议问题