From: Robert Klemme Date: 2007-09-03T22:55:23+09:00 Subject: Re: assigning to hash keys when there is a default value? 2007/9/3, dblack@wobblini.net : > Hi -- > > On Mon, 3 Sep 2007, Russell Norris wrote: > > > I learned that x ||= y means set x to y unless x, so I don't see the > > bug. and i don't see this as being at all unpredictable. either way > > you expect it to work, it either fails 100% or succeeds 100%. :) the > > only problem is when you expect it to do something it doesn't do, > > which is tautologically what every problem is i guess. > > I guess one can just accomodate oneself to whatever happens, in which > case there are no bugs... but somehow it never seems to play out that > way :-) Anyway, we're going around in circles. I think I might hop > over to ruby-core and see what people think. Will be interesting to hear what they say. In the meantime: I believe we're discussing something that's not an issue most of the time, because even if there is no assignment with the default value, querying will still return the same result. The only possible issue here is that Hash#keys returns something different depending on the implementation. Why do I think there is no problem most of the time? Let's look at some typical idioms which work as we like them to work: counters = Hash.new 0 ... counters[item] += 1 counters.each do |key,value| printf "%5d %s\n", value, key end lists = Hash.new {|h,k| h[k] = []} ... lists[key] << item lists.each do |key,list| print key, " ", list.inspect, "\n" end I wonder where we would actually use ||= with a Hash. Is this a realistic example? found = Hash.new ... found[item] ||= true I don't think so, because in that case I'd rather use found[item] = true Is ||= really used with Hash at all? I can't think of a case ATM but that might just be my limited fantasy. :-) Kind regards robert