Hi --

On Wed, 6 Dec 2006, Andreas Warberg wrote:

> I am new to Ruby but have a strong java background.
>
> So far I have been enjoying Ruby a great deal.
>
> But I have been wondering about why the scope of variables works as it
> does. It seems that very often, I need to prefix my variables with
> either @ or $ in order to access them in method calls.
> I did some searching for an explanation but did not find any.
>
> In java variables can be defined and used like this:
>
> Object x = myX;
>
> public void printx(){
>    System.out.println(x);
> }
>
> x is available when the method is called. This is not the case with
> Ruby:
>
> x = myX
>
> def printx
>   puts x
> end
>
> Running the code will produce an error: "NameError: undefined local
> variable or method `x' for main:Object".
>
> In order to reveal x to the method one must, for instance, declare it
> global by prefixing the $. This requires more typing (which, in many
> other respects, ruby tries to avoid).
>
> How come the scope works in this way? I expected the visibility of
> variables to flow down into the code tree (but not up, of course).

def starts a new local scope, so local variables defined outside it
won't be visible.  I can't answer the question defensively -- that is,
I can't say why it is in relation to Java, since I have no reason to
think it was designed in relation to Java :-)

Instance variables (@this) are always associated with, and owned by,
whatever object is in the role of "self", the default object.  Inside
a method definition, self is (or is going to be, when the method
eventually gets called) the object running the method.

Global variables ($this) are just global variables, and have the usual
properties of such variables: they walk through walls, so to speak,
when it comes to scope, and generally discourage nice encapsulation of
code and interaction of objects.


David

-- 
                   David A. Black | dblack / wobblini.net
Author of "Ruby for Rails"   [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog)        [2] | Co-director, Ruby Central, Inc.   [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com    | [4] http://www.rubycentral.org