From: Paul Lutus Date: 2006-12-06T01:45:05+09:00 Subject: Re: Unexpected scope range 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. -- Paul Lutus http://www.arachnoid.com