简体   繁体   中英

Why does instance_eval succeed with a Proc but not with a 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 does the second instance_eval fail with a wrong number of arguments (1 for 0) error?

instance_eval is yielding self ( User ) to the lambda. Lambdas are particular about their parameters - in the same way methods are - and will raise an ArgumentError if there are too few/many.

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's the difference between a proc and a lambda in Ruby?

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 to the given block, so wrong number of arguments (1 for 0) won't be thrown.

Look here for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM