From: Chuck Remes Date: 2008-08-08T10:36:14+09:00 Subject: Re: Most compact command for associate array 'totalling'? On Aug 7, 2008, at 5:27 PM, Siep Korteling wrote: > Chuck Remes wrote: >> On Aug 7, 2008, at 4:59 PM, John Pritchard-williams wrote: >> >>> >>> 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 > > a = Hash.new(0) > a["abc"] += 1 > > Has the same effect. Quite true, but I find the block form to be a better "general case" form to know since it is so much more flexible. But that's just my preference. cr