Newbie Question: Global variable vs. Top-level variable

S

Sam Kong

Hi, group!

This morning, a question came into my mind (I'm still a newbie).
What's the meaning of a top-level variable?

t = "top"
$g = "global"

puts t
puts $g

def f
puts t #error
puts $g
end

f

I know that a top-level variable cannot be used in a method.

My questions are:

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?

2. What is a top-level variable? Is it an object variable or a local
variable or what?

3. What is the exact scope of a top-level variable?


Thanks.
Sam
 
L

Logan Capaldo

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
 
J

Joel VanderWerf

Logan said:
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.


Well liek I said its a local, and lexically scoped. So....

...and the scope is the _file_ in which that variable appears.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top