Ruby - Local and Global Variables

Introduction

Variables beginning with a lowercase character are called local variables.

They exist only within a specific part of a program.

They are restricted to a well-defined scope. Here is an example:

Demo

localvar = "hello" 
$globalvar = "goodbye"  

def amethod # w w w  .  j  a va  2  s  . c  om
    localvar = 10 
    puts( localvar ) 
    puts( $globalvar ) 
end 

def anotherMethod 
    localvar = 500 
    $globalvar = "bonjour" 
    puts( localvar ) 
    puts( $globalvar ) 
end

Here, there are two functions, amethod and anotherMethod.

Each of which is declared using the keyword def and contains code up to the keyword end.

There are three local variables called localvar.

One is assigned the value "hello" within the "main scope" of the program.

Two others are assigned integers within the scope of two separate methods.

Since each local variable has a different scope, the assignments have no effect on the other local variables with the same name in different scopes.

A global variable, one that begins with the dollar sign character $, has global scope.

When an assignment is made to a global variable inside a method, that affects the value of that variable else where.