From: "s.ross" Date: 2008-02-20T07:43:38+09:00 Subject: Re: ||= [] idiom If you don't mind being really cryptic about it: @categories = resource.inject({}) {|a, v| (a[v.tag] ||= []) << v; a} I think this works, but I'm not sure the "next guy" would ever figure out what it does :) On Feb 19, 2008, at 2: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 If you don't mind being really cryptic about it: @categories = resource.inject({}) {|a, v| (a[v.tag] ||= []) << v; a} I think this works, but I'm not sure the "next guy" would ever figure out what it does :)