When to use local variables in Ruby Classes



Hey C9,

I get the abstract idea of local and instance variables… In fact, the same definition is out there on the web on each and every single website…

However, can someone please share a real world simple example of when a local variable would be useful and necessary within a class, in ruby of course?

Thank You,
Bryan G.


Hi Bryan,

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;

def foo
    puts localVar

foo #=> NameError: undefined local variable or method...

def bar
    var1 = 50;
    if true do
        puts var1

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:

class Test
    fooVar = 10

    define_method :foo do 
      puts fooVar


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_reader, :attr_writer, or :attr_accessor for instance variables to provide encapsulation. You can also override the methods (say the instance variable name is foo) 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.




thanks that cleared up alot… I truly appreciate it… and you’re right. I will take these questions to stack overflow.