From: Chuck Remes Date: 2008-08-08T07:12:34+09:00 Subject: Re: Most compact command for associate array 'totalling'? On Aug 7, 2008, at 4:59 PM, John Pritchard-williams wrote: > Ok - in 'awk' you can do this: (Where 'array' is empty initially) > > array[]++ > > > For instance: > > array["abc"]++; => a["abc"]=1 > array["abc"]++; => a["abc']=2 > ... > > Which is really useful for tallying up a complete column of varying > values from a text file where you don't know in advance the what may > appear in a column etc... > > In Ruby, I have worked out a similar the equivalent to be: (with a > Hash > now...) > > > a={}; > a["abc"]=a["abc"].to_i+1; > > > But I"m sure there is a shorter way ? Better trick available here? > > As an aside to 'to_i' is to turn the 'nil' into zero: is this safe to > assume this? > > Thanks - sorry if this is stupid question.... No stupid questions; they're all good. Here's a minor reworking of what you did to eliminate the #to_i. a = Hash.new { |h,k| h[k] = 0 } a["abc"] += 1 The special form of Hash.new that I used above will automatically initialize the bucket to 0 for any new key it receives, so you avoid the problem with nil and #to_i. cr