From: Josh Cheek Date: 2011-12-06T08:58:52+09:00 Subject: Re: black magical hash element vivification --f46d04428ee299d04304b3611955 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable 2011/12/5 Jes=FAs Gabriel y Gal=E1n > On Mon, Dec 5, 2011 at 9:05 PM, Chad Perrin wrote: > > On Tue, Dec 06, 2011 at 01:40:17AM +0900, Jes=FAs Gabriel y Gal=E1n wro= te: > >> > >> 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 =3D> true} for foo[2]. > > > > I find it rather surprising that assignment does not create something n= ew > > 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 i= t > > 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 =3D Hash.new(0) > #fill the hash > possible_keys =3D [:a, :b, :c, :d] # some of them might not be in the > histogram: > > average =3D (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] +=3D 1 > > Jesus. > > You can get that behaviour with Hash.new { 0 }, too. --f46d04428ee299d04304b3611955--