From: Josh Cheek Date: 2011-12-09T15:40:09+09:00 Subject: Re: How can I do h["foo"] += "bar" if h["foo"] does not exist? --f46d04428ee23d8a3904b3a30ea9 Content-Type: text/plain; charset=KOI8-R Content-Transfer-Encoding: quoted-printable On Fri, Dec 9, 2011 at 12:11 AM, Ryan Davis wrote= : > > On Dec 8, 2011, at 22:03 , Peter Zotov wrote: > > > Andrew S. =D0=C9=D3=C1=CC 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"] +=3D "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 ke= y > >> 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 th= e > >> hash. > >> > >> Any help gratefully received! > >> > >> - A > > > > $ irb > > ruby-1.9.3-p0 :001 > hash =3D Hash.new("") > > =3D> {} > > ruby-1.9.3-p0 :002 > hash[:a] =3D "test" > > =3D> "test" > > ruby-1.9.3-p0 :003 > hash[:a] +=3D " - one" > > =3D> "test - one" > > ruby-1.9.3-p0 :004 > hash[:b] +=3D "nothing - two" > > =3D> "nothing - two" > > ruby-1.9.3-p0 :005 > hash > > =3D> {:a=3D>"test - one", :b=3D>"nothing - two"} > > This is bad. Very bad. > > irb(main):007:0> hash[:d] << "blah" > =3D> "blah" > irb(main):008:0> hash[:e] +=3D " blah" > =3D> "blah blah" > irb(main):009:0> hash > =3D> {:b=3D>"nothing - two", :e=3D>"blah blah", :c=3D>"blah", :a=3D>"test= - one"} > > Make sure you use the block form initializer whenever you have a mutable > default object. > > > > Additionally: hash =3D Hash.new("") # modifying the key doesn't set the key hash[:foo] << 'blah' hash.keys # =3D> [] # it modifies the default hash.default # =3D> "blah" hash[:foo] # =3D> "blah" hash[:bar] # =3D> "blah" --f46d04428ee23d8a3904b3a30ea9--