Thanks for writing in. I’m don’t think this question is related to Cloud9, and StackOverflow would probably be a better forum for this, but I’ll try to answer your question nonetheless. Also, please note that I’m not too knowledgeable about Ruby, so there will probably be a lot of things that I’ll miss in the following explanation:
So, firstly, what’s a local variable. A local variable in ruby is a variable that cannot be accessed outside the scope it was declared in. Usually all child scopes also inherit the variable, but there are two boundaries where local variables are not transported over:
The following example should explain:
localVar = 50;
foo #=> NameError: undefined local variable or method...
var1 = 50;
if true do
bar #=> 50
Looking at this scenario, if you declare a variable within a class, it cannot be accessed by the class’s methods. Instance variables can be used by all methods of the class instance.
This severely limits the actual use of local variables within classes. There are ways you can work around this restriction, for example, by using lambdas or procs. For example, in order to use a local variable with a class, you can do the following:
fooVar = 10
define_method :foo do
test = Test.new
test.foo #=> 10
The cool thing about the above is that this variable is now unusable by all ‘methods’ of the class instance, other than the ones using
define_method and a proc. However, in practice, such tricks lead more to confusion and less towards anything actually useful.
This is still a fairly long topic, but here’s what I make of it in short:
Use instance variables within classes, and use
:attr_accessor for instance variables to provide encapsulation. You can also override the methods (say the instance variable name is
def foo ... end and
def foo= ... end to control how an instance variable is written.
As far as I can see (and I could be wrong here), there’s no actual benefit to using local variables within classes.
I hope this helps.