![](/img/trans.png)
[英]Why does instance_eval succeed with a Proc but not with a Lambda?
[英]Why am I getting an error calling instance_eval with to_proc and not with Proc.new?
我正在这样做,它的工作原理是:
class B
def value
"X"
end
end
class A
def initialize(context)
@context = context
end
def m
Proc.new do
value
end
end
def execute
@context.instance_eval(&m)
end
end
A.new(B.new).execute #=> "X"
但是调用m.to_proc
无法正常工作...
class B
def value
"X"
end
end
class A
def initialize(context)
@context = context
end
def m
value
end
def execute
@context.instance_eval(&m.to_proc)
end
end
A.new(B.new).execute #=> NameError: undefined local variable or method `value' for #<A:0x007fae2ab02040 @context=#<B:0x007fae2ab02108>>
我想知道这两个示例为何不同,以及如何使其与to_proc
在第二个片段中,您正在调用m
,该value
返回未定义的调用value
的结果。 ( 即使如果不知何故神奇地调用B#value
,则B#value
返回一个String
和String
■不要回应to_proc
,所以你会得到一个NoMethodError
那里。)在第一个片段,你叫m
,它返回一个Proc
。
看起来您正在尝试传递方法m
本身,而不是调用它的结果。 在Ruby中,方法不是对象,所以您不能只是抓住它们并传递它们(即使方法是对象,那么m
仍然是调用m
的语法,而不是引用它的语法)。 您必须首先使用Object#method
方法向Ruby的反射API请求该方法的反射代理,该方法返回代表该方法的Method
对象:
@context.instance_eval(&method(:m).to_proc)
注意,这里对to_proc
的调用是完全多余的,因为如果参数还不是Proc
,则&
仍然会调用to_proc
。 (您之前可能已经看过类似foo.map(&:bar)
东西,它将调用Symbol#to_proc
。)
@context.instance_eval(&method(:m))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.