From: Ryan Davis Date: 2011-12-09T15:07:17+09:00 Subject: Re: How can I do h["foo"] += "bar" if h["foo"] does not exist? On Dec 8, 2011, at 21:58 , Andrew S. wrote: > Hi there, > > I have a hash with various keys and values that are strings. > > If the key exists, the following works: h["foo"] += "bar" That only works if the value at key "foo" responds to +. In this case, I presume, a String. > But if the key does not exist, I get an error. You only get an error because nil (the default default value) doesn't respond to +. > Is it possible _in one statement_ to cover both the cases where the key > does exist (as above) AND the case where the key does not exist - and in > this situation I'd like the new key and value pair to be created in the > hash. Assuming you want an empty string as your default value: h = Hash.new { |h,k| h[k] = "" } That will initialize your hash 'h' with a default value proc that gets run every time you access a key that isn't yet a member of h. That proc is passed the hash (self) and they key. We assign a new empty string at h[k].