How to use global variables in Ruby?

Global variables have a global scope and they can be accessed from anywhere in a program. Assignments to global variables can be made from anywhere in the program. Global variables are always prefixed with a dollar sign.

It is necessary to define a global variable to have a variable that is available across classes. When a global variable is uninitialized, it has no value by default and its use is nil.

Now let's make use of the global variable in an example to understand it better. Consider the code shown below.

Example 1

# Global Variable example

# global variable
$global_var = 15

# Defining first class
class FirstClass
   def print_global_variable
      puts "Global variable in FirstClass is #$global_var"

# Defining second Class
class SecondClass
   def print_global_variable
      puts "Global variable in SecondClass is #$global_var"

# Creating object
firstclassobj =

# Creating another object
secondclassobj =


Global variable in FirstClass is 15
Global variable in SecondClass is 15

Example 2

Now, let's explore one more example of a global variable in Ruby. Consider the code shown below.

# global variable example
$global_var = "Tutorial"

# Defining Class
class Teacher
   def instance_method
      puts "Available? #{$global_var}, #{$some_global_var}"

   def self.class_method
      $some_global_var = "Welcome to TutorialsPoint"
      puts "Available? #{$global_var}"



Available? Tutorial

Updated on: 25-Jan-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started