문제

I found out this morning that proc.new works in a class initialize method, but not lambda. Concretely, I mean:

class TestClass

  attr_reader :proc, :lambda

  def initialize
    @proc = Proc.new {puts "Hello from Proc"}
    @lambda = lambda {puts "Hello from lambda"}
  end

end

c = TestClass.new
c.proc.call
c.lambda.call

In the above case, the result will be:

Hello from Proc
test.rb:14:in `<main>': undefined method `call' for nil:NilClass (NoMethodError)

Why is that?

Thanks!

도움이 되었습니까?

해결책

The fact that you have defined an attr_accessor called lambda is hiding the original lambda method that creates a block (so your code is effectively hiding Ruby's lambda). You need to name the attribute something else for it to work:

class TestClass

  attr_reader :proc, :_lambda

  def initialize
    @proc = Proc.new {puts "Hello from Proc"}
    @_lambda = lambda {puts "Hello from lambda"}
  end

end

c = TestClass.new
c.proc.call
c._lambda.call
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top