这里发生了什么? (Ruby 中为零)

发布于 2024-09-18 04:04:52 字数 250 浏览 4 评论 0原文

p parent.class #=> NilClass # ok.
p !!parent # => false # as expected.
p parent.object_id # => 17006820 # should be 4
p parent && parent.foo # => NoMethodError foo # should be nil-guarded

这个对象从哪里来?

p parent.class #=> NilClass # ok.
p !!parent # => false # as expected.
p parent.object_id # => 17006820 # should be 4
p parent && parent.foo # => NoMethodError foo # should be nil-guarded

Where does this object come from?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

债姬 2024-09-25 04:04:52

可能是这样的:

class BlankSlate
  instance_methods.each do |m|
    # Undefine all but a few methods. Various implementations leave different
    # methods behind.
    undef_method(m) unless m.to_s == "object_id"
  end
end

class Foo < BlankSlate
  def method_missing(*args)
    delegate.send(*args)
  end

  def delegate
    # This probably contains an error and returns nil accidentally.
    nil
  end
end

parent = Foo.new

p parent.class
#=> NilClass

p !!parent
#=> false

p parent.object_id
#=> 2157246780

p parent && parent.foo
#=> NoMethodError: undefined method `foo' for nil:NilClass

创建 BlankSlateBasicObject 是一种常见模式(在 1.9 版将其添加到核心 Ruby 之前)。它用于创建对象,这些对象将使用它们发送的任何方法执行一些特殊操作,或者将它们的行为大量委托给不同的类。缺点是它可能会引入这样的奇怪行为。

Possibly something like this:

class BlankSlate
  instance_methods.each do |m|
    # Undefine all but a few methods. Various implementations leave different
    # methods behind.
    undef_method(m) unless m.to_s == "object_id"
  end
end

class Foo < BlankSlate
  def method_missing(*args)
    delegate.send(*args)
  end

  def delegate
    # This probably contains an error and returns nil accidentally.
    nil
  end
end

parent = Foo.new

p parent.class
#=> NilClass

p !!parent
#=> false

p parent.object_id
#=> 2157246780

p parent && parent.foo
#=> NoMethodError: undefined method `foo' for nil:NilClass

Creating BlankSlate or BasicObject is a common pattern (before it was added to core Ruby as of version 1.9). It serves to create objects that will do something special with any method they are sent, or heavily delegate their behaviour to a different class. The downside is that it may introduce strange behaviour like this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文