Ruby 这里发生了什么事?(红宝石为零)
这个物体从哪里来?可能是这样的:Ruby 这里发生了什么事?(红宝石为零),ruby,null,Ruby,Null,这个物体从哪里来?可能是这样的: 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 实例|u方法。
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
实例|u方法。每个方法都有| m|
#取消定义除少数方法外的所有方法。不同的实现会留下不同的结果
#方法落后。
未定义方法(m),除非m.to_s==“对象\u id”
结束
结束
Foo类零级
P父母亲
#=>错误
p parent.object\u id
#=> 2157246780
p parent&&parent.foo
#=>NoMethodError:nil:NilClass的未定义方法'foo'
创建
BlankSlate
或BasicObject
是一种常见的模式(从版本1.9开始添加到CoreRuby之前)。它用于创建对象,这些对象将对所发送的任何方法执行特殊操作,或者将其行为严重委托给不同的类。缺点是它可能会引入类似这样的奇怪行为。sepp2k可以做出很好的假设,但现在,这里没有真正的问题。很好。(rdb:1)p Object.instance_方法(:class).bind(parent).call YARD::StubProxy
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