From: Robert Klemme Date: 2009-03-03T05:53:57+09:00 Subject: Re: Newbie question > Hash workings On 02.03.2009 19:18, Adam Gardner wrote: > Robert Klemme wrote: >> On 01.03.2009 12:35, AD60 wrote: >>> I see the use with an integer default, I specifically meant the >>> Hash.new([]) syntax as problematic, but it probably all depends on >>> knowing what your doing. >> Ah. Since you talked about "idiom" I thought you were referring to the >> general pattern. >> >>> Just to detail the difference: >>> >>> hav = Hash.new { |h,k| h[k] = []} >>> hav[0] += [1] >> Actually this is very inefficient. With this idiom you should rather do >> >> hav[0] << [1] >> >> because otherwise you'll end up creating and deleting Array instances >> all the time without any benefit. >> >>> it's the difference between "{0=>[1], 1=>[]}" and "{0=>1}" result that >>> had me wondering. Anyway thanks again, I understand how to use it and >>> that's more than enough for now. >> Good. > The method I would use is this: > > hav = Hash.new {[]} > > This gives you the benefit of creating a new array when necessary > (rather than a single default array which can be destructively modified > in troubling ways), but means that you only get permanent effects if you > explicitly use assignment, so you don't get this > > p hav # {0=>[1]} > p hav[1] # [] > p hav # {0=>[1], 1=>[]} > > Of course, it means you can't use the << operator to stick values into > non-present keys, but I rarely use the << operator anyway. You probably should get rid of that habit. And here's why: your approach has no means to efficiently work with Arrays as Hash values. Either, you have to use += all the time which is inefficient because it will create a lot of garbage - or you have to explicitly test for presence of the key, which is less efficient than letting Hash's C implementation do it. It is much more elegant to just always do hash[key] << value. If you just want to make sure that you always get an Array back, you could as well use Hash.new([].freeze) to avoid accidentally appending to the single default all the time. But it's a free country so if you like to stick with your habits... Cheers robert