Is there a ruby method that just returns the value of a block?

后端 未结 2 1866
借酒劲吻你
借酒劲吻你 2020-12-20 09:37

I know about Object#tap, which takes a value and returns that value. But is there a method that takes a block and returns the value evaluated by the block?

2条回答
  •  隐瞒了意图╮
    2020-12-20 09:46

    I think you could solve it with fibers. Something like:

    def myfiber
        block = lambda{nil}
        loop{ block = Fiber.yield(block.call) } 
    end
    f = Fiber.new {myfiber }
    f.resume
    
    puts "result: #{f.resume(lambda{1})}"
    puts "result: #{f.resume(lambda{5})}"
    puts "result: #{f.resume(lambda{2})}"
    

    will result in:

    result: 1
    result: 5
    result: 2
    

提交回复
热议问题