Newbie Question: Global variable vs. Top-level variable

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

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?

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?

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

x = 1

def a
x #error
end

# blocks are closures so....

c= lambda do |a|
     x + a # ok
end

class Q
     x #also an error
end

···

On 5/25/05, Sam Kong <sam.s.kong@gmail.com> wrote:

Thanks.
Sam

Logan Capaldo wrote:
...

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?

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

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

···

On 5/25/05, Sam Kong <sam.s.kong@gmail.com> wrote: