On Dec 8, 2011, at 21:58 , Andrew S. wrote:

> Hi there,
>=20
> I have a hash with various keys and values that are strings.
>=20
> If the key exists, the following works: h["foo"] +=3D "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 =3D Hash.new { |h,k| h[k] =3D "" }

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].