From: Robert Klemme Date: 2005-10-12T23:11:53+09:00 Subject: Re: Hash as a class variable OliverMarchand wrote: > Hi ruby fans, > > I am a python2ruby switcher and just encountered this problem today > with a class variable: > > --- > class Testclass > @@myhash = Hash.new({"a"=>"aaaah"}) > def initialize() > p @@myhash > end > end > T = Testclass.new > --- > yields > {} >> class Testclass >> @@myhash = {"a"=>"aaaah"} >> def initialize() >> p @@myhash >> end >> end => nil >> T = Testclass.new {"a"=>"aaaah"} => # You are providing a default value to the hash: >> h=Hash.new("foo") => {} >> h[1] => "foo" >> h[2] => "foo" >> h => {} If you need to create a filled hash using {} is enough. There is no such thing as a copy constructor. If you need to explicitely call Hash.new you need to use #update: >> h=Hash.new("foo").update(1=>2, 3=>4) => {1=>2, 3=>4} >> h => {1=>2, 3=>4} >> h[111] => "foo" Note that update(1=>2, 3=>4) is a shortcut for update({1=>2, 3=>4}) Kind regards robert