4

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!

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

Calling Kernel.lambda is another option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.