Ruby Local and Global Variables Tutorial

In this section, we will learn what the local and global variables are and how to use them in Ruby.

Note: we’re assuming you’re familiar with Methods in Ruby.

What is local variable in Ruby?

A variable that is declared in the body of a method is called a local variable.

Such a variable is not accessible within the body of other methods and that’s one reason why it’s called a local variable!

Note that we say a local variable is local to its enclosing method! That means the variable is only accessible within the body of its enclosing method and that’s it! If we attempt to access a local variable from another method, we will get an error as a result.

Example: creating a local variable in Ruby

def func 
    first_name = "John"
    puts first_name

end 

def func_two 
    puts first_name
end 

func
func_two

Output:

John

undefined local variable or method `first_name' for main:Object

Here we have a local variable named `first_name` in the body of the func method. This variable is defined in this method and so we can easily access it in order to get its value or assign a new value to it whenever it’s needed.

But if we try to access the variable from the body of another method, we will get an error, as you see from the output of this example.

We got the error because we tried to call the variable from the body of the `func_two` method while this method has no idea about such a variable (again because the variable is defined in the body of another method).

What is global variable in Ruby?

Now on the opposite side of local variables, we have the global variables!

A global variable is the one we define by adding the dollar sign at the beginning of the name of a variable.

For example:

$first_name

It doesn’t matter if such a variable is defined inside or outside of the body of a method! As long as the variable starts with the dollar sign, it becomes a global variable automatically.

Be aware that such variables are accessible within the body of any method.

This means if you have two methods, both of them can access the global variable, get its value or change it to a new one and this change will be apparent to both methods.

Example: creating a global variable in Ruby

def func 
    $first_name = "Jack"
end 

def func_two 
    puts $first_name
end 

func
func_two

Output:

Jack

As you can see, we’ve defined the `$first_name` variable within the body of the func method and because this variable is starting with the dollar sign, it is global and hence accessible within the body of any method.

That’s why we could access the variable in the body of the `func_two` method as well.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies