--+QahgC5+KEYLbs62
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Sep 16, 2011 at 05:57:36AM +0900, Vladimir Van Bauenhoffer wrote:
> Chad Perrin:
> >
> > What exactly do you mean by "the normal way"?
>=20
> I meant like this: myhash =3D {}, sorry for being unclear.

There have already been some good answers to this, but I'll throw in
another formulation of the explanation:

    myhash =3D {:foo =3D> 'foo'}
    mystring =3D 'foo'

This assigns a hash literal to myhash and a string literal to mystring.

    myhash =3D {}
    mystring =3D ''

This assigns an *empty* hash literal to myhash, and an *empty* string
literal to mystring.  In the case of the hash, all attempts to access
hash keys return a value of nil.

    myhash =3D Hash.new
    mystring =3D String.new

This assigns an empty hash to myhash and an empty string to mystring much
as in the immediately previous case, but does so by explicitly using the
new constructor rather than explicit assignment of a hash literal and
string literal to their respective variable names.

    myhash =3D Hash.new(0)
    mystring =3D String.new('zero')

This assigns a hash to myhash whose default value for nonexistent strings
is 0, and a string to mystring whose value is 'zero'.

    myhash =3D Hash.new {|h,k| k.to_s }
    mystring =3D String.new { 'foo' }

This is where they diverge.  You can pass a block to Hash.new telling it
what default values should be used for as-yet undefined keys.  In this
case, with the hash (as h) and the key (as k) passed to the block as
parameters, myhash[:foo] will return 'foo'.  In the case of this
construction for mystring, the block is thrown away, and you still get an
empty string.

--=20
Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ]

--+QahgC5+KEYLbs62
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.14 (FreeBSD)

iEYEARECAAYFAk5ygVwACgkQ9mn/Pj01uKXJ+wCfezGmkJVz8pSeNtOrNvUaox2w
JSEAnjjXxwEO2b9Ub5jKmJFW6xanELv/
=D2XI
-----END PGP SIGNATURE-----

--+QahgC5+KEYLbs62--