On Mon, Dec 5, 2011 at 9:05 PM, Chad P. [email protected] wrote:
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.