ruby – 麻烦在块/ lambda内产生

我有以下 Ruby代码
# func1 generates a sequence of items derived from x
# func2 does something with the items generated by func1
def test(x,func1,func2)
    func1.call(x) do | y |
        func2.call(y)
    end
end

func1 = lambda do | x |
    for i in 1 .. 5
        yield x * i
    end
end

func2 = lambda do | y |
    puts y
end


test(2,func2) # Should print '2','4','6','8',and '10'

当然,这不起作用.

test.rb:11: no block given (LocalJumpError)
    from test.rb:10:in `each'
    from test.rb:10
    from test.rb:4:in `call'
    from test.rb:4:in `test'
    from test.rb:20

解决方法

Lambdas不会像常规方法那样隐式接受块,所以你的func1不能产生.改为:
func1 = lambda do |x,&blk|
  for i in 1 .. 5
    blk.call(x * i)
  end
end

具体来说,我认为这是因为yield会将控制权发送回调用者的块,这不包括lambda调用.所以下面的代码就像你“期待”一样:

def foo
  (lambda { |n| yield(n) }).call(5)
end
foo { |f| puts f }  # prints 5

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...