[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Newbie Question: Global variable vs. Top-level variable

Sam Kong

5/25/2005 4:10:00 PM

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

2 Answers

Logan Capaldo

5/25/2005 4:33:00 PM

0

On 5/25/05, Sam Kong <sam.s.kong@gmail.com> wrote:
> 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



> Thanks.
> Sam
>
>
>


Joel VanderWerf

5/25/2005 9:47:00 PM

0

Logan Capaldo wrote:
> On 5/25/05, Sam Kong <sam.s.kong@gmail.com> 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.