Ruby proc vs lambda in initialize ()

I found out this morning that proc.new works in the class initialization method, but not lambda. Specifically, 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 would be:

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

Why is this?

Thanks!

+4
source share
1 answer

The fact that you defined an attr_accessor called lambda hides the original lambda method that creates the block (so your code effectively hides Ruby lambda ). You need to name the attribute for something else:

 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 
+6
source

All Articles