为什么`class<<自我在Ruby' break'遗产?

时间:2014-11-06 21:48:46

标签: ruby

假设我有:

 class Parent
   def foo
     "foo"
   end
 end

 class Child < Parent
   class << self
 end

然后

 c = Child.new.foo

没有给我"foo"。为什么不呢?


上面的问题出现在我试图弄清楚为什么有些类的代码&lt;&lt;自我成语的表现方式我不明白。由于我在这篇文章中有语法错误,很明显我所看到的代码中的错误与class << self断开继承无关。我想删除这个Q.堆栈溢出不会让我。希望以后再发一个更好的问题。

3 个答案:

答案 0 :(得分:3)

此处存在语法错误。你永远不会关闭单身人士课程。应该是:

class Child < Parent
  class << self
  end
end

完美适合我:

irb(main):008:0> class Parent
irb(main):009:1>   def foo
irb(main):010:2>     "foo"
irb(main):011:2>   end
irb(main):012:1> end
=> :foo
irb(main):013:0> class Child < Parent
irb(main):014:1>   class << self
irb(main):015:2>     def foo
irb(main):016:3>       "class-foo"
irb(main):017:3>     end
irb(main):018:2>   end
irb(main):019:1> end
=> :foo
irb(main):020:0> c = Child.new
=> #<Child:0x000001021eae30>
irb(main):021:0> c.foo
=> "foo"
irb(main):022:0> Child.foo
=> "class-foo"

答案 1 :(得分:0)

 class Child < Parent
   class << self
 end

这个定义在语法上是无效的,没有意义。正确的定义是

 class Child < Parent
   class << self
   end
 end

但即使在这种情况下,除非你需要在单例类中定义一些内容,否则它完全没用。以下代码绰绰有余。

class Parent
   def foo
     "foo"
   end
end

class Child < Parent
end

这是一个例子

2.1.1 :010 > Child.new.foo
 => "foo" 

答案 2 :(得分:0)

你错过了&#34;结束&#34;。 class&lt;&lt;自我不是一个单行,并要求你关闭块。我只是使用额外的end运行您的代码,但它确实有效。

相关问题