Olivier
12/5/2006 9:16:00 PM
Le mardi 05 décembre 2006 17:45, Paul Lutus a écrit :
> 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).
>
> In Ruby, variables used within a method are marked this way:
>
> example # method local
> @example # class instance variable
> @@example # class variable
> $example # global variable
>
> The term "class variable" above refers to a variable that is common to the
> entire class, and "instance variable" refers to a variable that is unique
> to an instance of the class.
>
> This means you can use @this_syntax to refer to a variable you want to
> share between method within a class, without using global variables,
> something one wants to avoid unless necessary.
As a Java programmer, you are used to declare any attribute (ie instance
variables) in the "body" of the class, outside any method. This is not how it
works in Ruby, because no declaration is needed. So, as Paul wrote, you can
use directly @example within your methods with nothing more elsewhere.
If you are a bit confused of not having a place, in a class, where to put all
your instance variables, put it in the initialize method.
Note that int this class :
class A
@var
def meth
@var
end
end
the two @var are not the same !
About global variables, I personnaly never used them. It's useful for things
like $stdin or $DEBUG, but nothing more.
--
Olivier