From: Ryan Davis Date: 2011-12-09T15:11:19+09:00 Subject: Re: How can I do h["foo"] += "bar" if h["foo"] does not exist? On Dec 8, 2011, at 22:03 , Peter Zotov wrote: > 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"} This is bad. Very bad. irb(main):007:0> hash[:d] << "blah" => "blah" irb(main):008:0> hash[:e] += " blah" => "blah blah" irb(main):009:0> hash => {:b=>"nothing - two", :e=>"blah blah", :c=>"blah", :a=>"test - one"} Make sure you use the block form initializer whenever you have a mutable default object.