在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>
wo,等一下。這是什麼東西發送?看起來你正在反思某些東西,其語法看起來像是Ruby的一個深奧祕密。 – 2013-05-04 12:14:13
查看更新。 – DNNX 2013-05-04 12:21:05
啊,但我使用的是字符串,而不是這些:thingies(什麼都叫你......名字?) – 2013-05-04 12:40:04