On Wed, 20 Feb 2008 07:11:31 +0900, "Leslie Viljoen" <leslieviljoen / gmail.com> 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?

I sometimes do this sort of thing:

 ( @categories[resource.tag] ||= [] ) << resource

Although this might possibly be more readable:

 category = ( @categories[resource.tag] ||= [] )
 category << resource

Often it can make sense to factor the ||= portion into a
separate method:

 def category_for(tag)
   @categories[tag] ||= []
 end

 # ...

   category_for(resource.tag) << resource

-mental