From: William James Date: 2008-02-20T07:30:19+09:00 Subject: Re: ||= [] idiom On Feb 19, 4:11 pm, Leslie Viljoen wrote: > I often make use of this idiom to add something to an array in a hash of arrays: > > @categories = {} > > pagelist.each do |resource| > @categories[resource.tag] ||= [] > @categories[resource.tag] << resource > end > > . is there a better way? Can the two @categories lines > be made into one? > > Les irb(main):001:0> h = Hash.new { |hash, key| hash[key] =[] } => {} irb(main):002:0> h['foo'] << 33 => [33] irb(main):003:0> h['foo'] << 44 => [33, 44] irb(main):004:0> h => {"foo"=>[33, 44]}