2

我很困惑。当我在 Object 中定义一个方法时,我可以在 Objects超类BasicObject 中调用它!

像这样:

class Object
  def object_method
    "object_method called"
  end
end

Object.superclass.respond_to? :object_method
# => true

Object.superclass.object_method
# => "object_method called"

我原以为只有派生类才能继承新方法!

PS:我从ruby​​monk的练习中得出这个问题

.. 在 Object 中实现方法超类 ..

其中递归停止标准“受影响”。

4

2 回答 2

3

如您所见,它是一个派生类。

#ruby 1.8.7
Object.superclass
# => nil
nil.kind_of? Object
# => true

#ruby 2.0.0
Object.superclass
# => BasicObject 
BasicObject.kind_of? Object
# => true 
于 2013-06-04T00:48:30.737 回答
3

当你调用 时Object.superclass,你会得到一个描述BasicObject类的对象。

Class该对象是继承自 的类的实例Object。因此,它具有所有具有的方法Object,包括您添加的方法。

但是,BasicObject该类的实例没有此方法:

irb(main):122:0> Object.object_method
=> "object_method called"

irb(main):123:0> Object.new.object_method
=> "object_method called"

irb(main):124:0> Object.superclass.object_method  # Same as BasicObject.object_method
=> "object_method called"

irb(main):125:0> Object.superclass.new.object_method  # Same as BasicObject.new.object_method
NoMethodError: undefined method `object_method' for #<BasicObject:0x441743be>
        from (irb):125:in `evaluate'
        from org/jruby/RubyKernel.java:1065:in `eval'
        from org/jruby/RubyKernel.java:1390:in `loop'
        from org/jruby/RubyKernel.java:1173:in `catch'
        from org/jruby/RubyKernel.java:1173:in `catch'
        from ~/.rvm/rubies/jruby-1.7.0/bin/irb:13:in `(root)'

这里有更多的东西可以冥想:

irb(main):129:0> Object
=> Object
irb(main):130:0> Object.class
=> Class
irb(main):131:0> Object.new.class
=> Object
irb(main):132:0> Object.superclass
=> BasicObject
irb(main):133:0> Object.superclass.class
=> Class
irb(main):134:0> Object.superclass.new.class
NoMethodError: undefined method `class' for #<BasicObject:0x1c944d4a>
        from (irb):134:in `evaluate'
        from org/jruby/RubyKernel.java:1065:in `eval'
        from org/jruby/RubyKernel.java:1390:in `loop'
        from org/jruby/RubyKernel.java:1173:in `catch'
        from org/jruby/RubyKernel.java:1173:in `catch'
        from ~/.rvm/rubies/jruby-1.7.0/bin/irb:13:in `(root)'

玩得开心!

于 2013-06-04T01:11:26.953 回答