From: Logan Capaldo Date: 2007-07-05T12:21:26+09:00 Subject: Re: Isn't hash default value behavior just a little bizarre??? ------=_Part_76085_29699184.1183605688651 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 7/4/07, Farhad Farzaneh wrote: > > Try this: > > >> x = Hash.new([]) > => {} > >> x[:test] > => [] > >> x[:test] << 'this' > => ["this"] > >> x[:bar] > => ["this"] > > Huh? It seems that when I index a hash with a new key, it returns the > Hash's default value object, not a copy of it. So if you modify that, > it modifies the default value, which then effects the default value for > every other new key. > > I don't know, I wouldn't call this the "principle of least surprise"... > I was plenty surprised! > > -- > Posted via http://www.ruby-forum.com/. > > Copying is an interesting thing. For many objects there is a sane, obvious way to make a copy. But for many others it is not so clear. Consider for instance, Hash.new($stdin). What should it mean, in this context, to "copy" $stdin? Or consider Hash.new(some_very_large_object). Do you want a copy all the time? Luckily, Hash does have a mechanism to acheive what you want: >> x = Hash.new { |h,k| h[k] = [] } => {} >> x[:test] => [] >> x[:test] << 'this' => ["this"] >> x[:bar] => [] POLS also is matz.'s POLS. ------=_Part_76085_29699184.1183605688651--