From: Peter Zotov Date: 2011-12-09T15:03:13+09:00 Subject: Re: How can I do h["foo"] += "bar" if h["foo"] does not exist? Andrew S. писал 09.12.2011 09:58: > Hi there, > > I have a hash with various keys and values that are strings. > > If the key exists, the following works: h["foo"] += "bar" > > But if the key does not exist, I get an error. > > 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. > > Any help gratefully received! > > - A $ irb ruby-1.9.3-p0 :001 > hash = Hash.new("") => {} ruby-1.9.3-p0 :002 > hash[:a] = "test" => "test" ruby-1.9.3-p0 :003 > hash[:a] += " - one" => "test - one" ruby-1.9.3-p0 :004 > hash[:b] += "nothing - two" => "nothing - two" ruby-1.9.3-p0 :005 > hash => {:a=>"test - one", :b=>"nothing - two"} -- WBR, Peter Zotov.