From: "Jesús Gabriel y Galán" Date: 2011-12-06T07:18:44+09:00 Subject: Re: black magical hash element vivification On Mon, Dec 5, 2011 at 9:05 PM, Chad Perrin wrote: > On Tue, Dec 06, 2011 at 01:40:17AM +0900, Jesús Gabriel y Galán wrote: >> >> Using that Hash constructor, what you pass is the default value for a >> missing key. What this means is that the hash will return that object >> to any call in which the key is not found. *But* it won't assign that >> default object to the key. You have to do that yourself. The other >> effect you are seeing is that the default object is returned for all >> missing keys, hence the {2 => true} for foo[2]. > > I find it rather surprising that assignment does not create something new > where the default used to appear, and kind of useless in this context.  I > know it's a special case of assignment that causes this to occur, now > that I think about it after reading replies to my original email, but it > seems like a strange way to implement things from a language user > perspective. > > Thanks to everybody who responded. I think the surprise comes from the fact that you are using a mutable object, or at least an object that only makes sense when modified. There are some cases where it makes sense to have a default value that doesn't imply assigning it to the missing key. For example, say you have an histogram hash, and want to calculate the average of a certain set of values: histogram = Hash.new(0) #fill the hash possible_keys = [:a, :b, :c, :d] # some of them might not be in the histogram: average = (possible_keys.inject(0) {|total, element| total + histogram[element]} ) * 1.0 / possible_keys.length Here it totally makes sense to have 0 as the default value, and not have all possible_keys assigned in the hash when you are calculating an average for a set of keys that might or might not be in the hash. I think that allowing this version of the constructor along with the one where you have full control of what to do on a missing key, gives you all the flexibility for a lot of use cases. By the way, for the histogram case above, when you are counting things, you also take advantage of 0 being the default value like this: histogram[key] += 1 Jesus.