为什么第二个'p arg'报告 Foo 实例?
class Foo
def with_yield
yield(self)
end
def with_instance_eval(&block)
instance_eval(&block)
end
end
f = Foo.new
f.with_yield do |arg|
p self
# => main
p arg
# => #<Foo:0x100124b10>
end
f.with_instance_eval do |arg|
p self
# => #<Foo:0x100124b10>
p arg
# => #<Foo:0x100124b10>
end
为什么第二个“p arg
”报告 Foo 实例?因为 with_instance_eval
不会向块产生 self
,所以它不应该报告 nil
吗?
class Foo
def with_yield
yield(self)
end
def with_instance_eval(&block)
instance_eval(&block)
end
end
f = Foo.new
f.with_yield do |arg|
p self
# => main
p arg
# => #<Foo:0x100124b10>
end
f.with_instance_eval do |arg|
p self
# => #<Foo:0x100124b10>
p arg
# => #<Foo:0x100124b10>
end
Why does the second 'p arg
' report the Foo instance? Shouldn't it report nil
since with_instance_eval
does not yield self
to the block?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
显然,在 ruby 1.8 中,instance_eval 不仅将块内的 self 值更改为其接收者,还生成该值。在 1.9 中,情况不再如此(那里 arg 将为 nil),因此不应依赖该行为(我也很确定它没有记录)。
Apparently in ruby 1.8 instance_eval does not only change the value of self inside the block to its receiver, it also yields that value. In 1.9 this is no longer the case (arg will be nil there), so that behavior should not be relied upon (I'm also pretty sure it's undocumented).