繁体   English   中英

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

[英]What happend here? (nil in 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

这个物体从哪里来?

可能是这样的:

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中之前)。 它用于创建对象,这些对象将对发送它们的任何方法进行特殊处理,或将其行为大量委派给其他类。 缺点是它可能会引入类似的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM