ruby - Class level variable acts like an instance variable instead -
i'm new ruby, being called upon maintain old, undocumented code here , there. have base class in ruby put hash class variable.
@@projects = hash.new
and want derived classes add via method (passing in parameter). problem is, seems each derived class has own copy of hash, instead of accessing single 'static' version of it.
could help?
class base @@projects = hash.new def addsomething key, value @@projects[key] = value end end class derived < base def initialize ... addsomething key, value ... end end
so, in code sample above, every time add value @@projects in addsomething function size/length of hash 1, never grows. acts if it's instance variable not want.
any ideas? i'm stumped here.
probably wrong in code hidden behind ...
in initializer of derived. code below works me fine:
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: let me put differently:
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>
Comments
Post a Comment