On 5/25/05, Sam Kong <> wrote:
> Hi, group!
>=20
> This morning, a question came into my mind (I'm still a newbie).
> What's the meaning of a top-level variable?
>=20
> t =3D "top"
> $g =3D "global"
>=20
> puts t
> puts $g
>=20
> def f
> puts t #error
> puts $g
> end
>=20
> f
>=20
> I know that a top-level variable cannot be used in a method.
>=20
> My questions are:
>=20
> 1. Do you use top-level variables instead of global variables if you
> don't need to use it in a method? Is it a good practice to use it like
> that?
>=20
If you're writing a short script with no methods (or very few) its a
not a big deal.
> 2. What is a top-level variable? Is it an object variable or a local
> variable or what?
>
It's a lexically scoped local. You can imagine the top level as sort
of being inside it's own implicit method that automatically gets
called. (not really true, but works as far as scope is concernced.
> 3. What is the exact scope of a top-level variable?
>=20
>=20
Well liek I said its a local, and lexically scoped. So....
x =3D 1
def a
x #error
end
# blocks are closures so....
c=3D lambda do |a|
x + a # ok
end
class Q
x #also an error
end
> Thanks.
> Sam
>=20
>=20
>
|