Ruby - Class Local Variables

Introduction

Consider the following code:

Demo

x = 10 
puts x

Result

In Ruby, this sort of variable is called a local variable.

It can be used only in the same place it is defined.

It's considered to be local in scope.

It's only present within the local area of code.

def basic_method 
  puts x 
end 

x = 10 
basic_method 

This example defines x to equal 10, and then jumps to a local method called basic_method.

If you ran this code, you would get an error like this:

NameError: undefined local variable or method 'x' for main:Object 
        from (irb):2:in 'basic_method' 

When you are in basic_method, you're no longer in the same scope as the variable x.

Because x is a local variable, it exists only where it was defined.

To avoid this problem, use only local variables where they're being directly used.

Here's an example where you have two local variables with the same name but in different scopes:

Demo

def basic_method 
  x = 50 #  ww w . j  a  v a  2 s .  c  o  m
  puts x 
end 

x = 10 
basic_method 
puts x

Result

Here, you set x to 10 in the main code, and set x to 50 inside the method.

x is still 10 when you return to the original scope.

The x variable inside basic_method is not the same x variable that's outside of the method.

They're separate variables, distinct within their own scopes.