这里发生了什么? (Ruby 中为零)
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能是这样的:
创建
BlankSlate
或BasicObject
是一种常见模式(在 1.9 版将其添加到核心 Ruby 之前)。它用于创建对象,这些对象将使用它们发送的任何方法执行一些特殊操作,或者将它们的行为大量委托给不同的类。缺点是它可能会引入这样的奇怪行为。Possibly something like this:
Creating
BlankSlate
orBasicObject
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.