From: Adam Gardner Date: 2009-03-03T03:18:10+09:00 Subject: Re: Newbie question > Hash workings 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. > > Kind regards > > robert 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. -- Posted via http://www.ruby-forum.com/.