【问题标题】:Why does the second 'p arg' report the Foo instance?为什么第二个 'p arg' 报告 Foo 实例?
【发布时间】:2010-11-28 13:03:41
【问题描述】:
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 实例?它不应该报告nil,因为with_instance_eval 不会产生self 到块?

【问题讨论】:

标签: ruby instance-eval


【解决方案1】:

显然,在 ruby​​ 1.8 中 instance_eval 不仅将块内的 self 的值更改为它的接收者,它还产生了该值。在 1.9 中不再是这种情况(arg 将在那里为零),因此不应依赖这种行为(我也很确定它没有记录)。

【讨论】:

    猜你喜欢
    • 2013-12-27
    • 2017-04-06
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    相关资源
    最近更新 更多