Pregunta

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!

¿Fue útil?

Solución

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top