可能隐藏...
在 Derived 的初始化程序中的代码有问题。下面的代码对我来说很好:
irb(main):032:0> class Base
irb(main):033:1> @@projects = {}
irb(main):034:1> def add(k, v)
irb(main):035:2> @@projects[k] = v
irb(main):036:2> end
irb(main):037:1> end
=> nil
irb(main):038:0> class Derived < Base
irb(main):039:1> def initialize(k, v)
irb(main):040:2> add(k, v)
irb(main):041:2> end
irb(main):042:1> end
=> nil
irb(main):048:0> Derived.send(:class_variable_get, :@@projects)
=> {}
irb(main):049:0> Derived.new(1,2)
=> #<Derived:0xb777be6c>
irb(main):050:0> Derived.send(:class_variable_get, :@@projects)
=> {1=>2}
irb(main):051:0> Derived.new(3,4)
=> #<Derived:0xb7772fb0>
irb(main):052:0> Derived.send(:class_variable_get, :@@projects)
=> {1=>2, 3=>4}
UPD:让我换种说法:
irb(main):053:0> class Base
irb(main):054:1> @@projects = {}
irb(main):055:1> def add(k, v)
irb(main):056:2> @@projects[k] = v
irb(main):057:2> p @@projects
irb(main):058:2> end
irb(main):059:1> end
=> nil
irb(main):060:0> class Derived < Base
irb(main):061:1> def initialize(k, v)
irb(main):062:2> add(k, v)
irb(main):063:2> end
irb(main):064:1> end
=> nil
irb(main):065:0>
irb(main):066:0* Derived.new(1, 2)
{1=>2}
=> #<Derived:0xb77ae40c>
irb(main):067:0> Derived.new(:a, :b)
{:a=>:b, 1=>2}
=> #<Derived:0xb77a0500>
irb(main):068:0> Derived.new(:c, :d)
{:a=>:b, :c=>:d, 1=>2}
=> #<Derived:0xb779ace0>