[英]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
失败并且wrong number of arguments (1 for 0)
错误?
instance_eval
is yielding self
( User
) to the lambda. instance_eval
正在向lambda产生self
( User
)。 Lambdas are particular about their parameters - in the same way methods are - and will raise an ArgumentError
if there are too few/many. Lambdas特别关注它们的参数 - 与方法相同 - 并且如果太少/很多则会引发
ArgumentError
。
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? 相关: Ruby中的proc和lambda有什么区别?
If you still want to use lambda, this code will work: 如果您仍想使用lambda,此代码将起作用:
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. instance_exec
相反的instance_eval
不会将self
作为给定块的参数提供,因此不会抛出wrong number of arguments (1 for 0)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.