From: Sean Chittenden Date: 2001-07-11T17:00:52+09:00 Subject: [ruby-talk:17641] Re: Hash as an instance variable... --ggHp9WSrPOeNxb0b Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable This makes complete sense and was what I thought was happening. =20 None-the-less it was still a decent gotcha that I wasn't expecting. =20 This was a very helpful response, thank you. Maybe this code snippet=20 could make its way into the next Programming Ruby book. ;~) -sc > > class Testing > > @test_hash =3D Hash.new() > >=20 > > public > > def set(key, val) > > @test_hash[key] =3D val > > end > > end >=20 > That's a Java idiom that doesn't mean the same thing in Ruby. In a class > definition, outside of a method definition, you are in the context of the > *class* object, not the instance. So what you're doing there is defining > a class instance variable (sort of, but not really at all, like a static > variable in Java), whereas when you did it inside the initialize method > you were defining an instance variable. >=20 > This is confusing. The short answer is, do it in the initialize instead. >=20 > For a start at the long answer, try this: >=20 > class Testing >=20 > @var =3D "class" > =09 > def initialize > @var =3D "instance" > end >=20 > def Testing.print > puts @var > end >=20 > def print > puts @var > end > end >=20 > t =3D Testing.new > t.print > Testing.print --=20 Sean Chittenden --ggHp9WSrPOeNxb0b Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Comment: Sean Chittenden iEYEARECAAYFAjtMB7AACgkQn09c7x7d+q2a0QCfdChyTj/KGykiuoG6wbV/gUXl WtIAn2T9KqnxKV+vFQn/6ijLKvEce5HN =RWWu -----END PGP SIGNATURE----- --ggHp9WSrPOeNxb0b--