Why does instance_eval succeed with Proc but not with Lambda?

I have the following class:

class User code1 = Proc.new { } code2 = lambda { } define_method :test do self.class.instance_eval &code1 self.class.instance_eval &code2 end end User.new.test 

Why did the second instance_eval fail with the wrong number of arguments (1 for 0) error?

+7
source share
2 answers

instance_eval gives self ( User ) lambda. Lambdas is especially concerned with its parameters - just like methods - and will raise an ArgumentError if there are too few of them.

 class User code1 = Proc.new { |x| x == User } # true code2 = lambda { |x| x == User } # true define_method :test do self.class.instance_eval &code1 self.class.instance_eval &code2 end end 

Relevant: What is the difference between proc and lambda in Ruby?

+13
source

If you still want to use lambda, this code will work:

 block = lambda { "Hello" } # or -> { "Hello" } some_obj.instance_exec(&block) 

instance_exec contrary to instance_eval will not supply self as an argument for this block, so the wrong number of arguments (1 for 0) will not be selected.

Look here for more information.

+4
source

All Articles