Open In App

Global Variable in Ruby

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Global Variable has global scope and accessible from anywhere in the program. Assigning to global variables from any point in the program has global implications. Global variable are always prefixed with a dollar sign ($). If we want to have a single variable, which is available across classes, we need to define a global variable. By default, an uninitialized global variable has a nil value and its use can cause the programs to be cryptic and complex. Global variable can be change anywhere in program.
Syntax :

$global_variable = 5

Example :




# Ruby Program to understand Global Variable
  
# global variable 
$global_variable = 10
  
# Defining class
class Class1 
 def print_global 
 puts "Global variable in Class1 is #$global_variable"
 end
end
  
# Defining Another Class
class Class2 
 def print_global 
 puts "Global variable in Class2 is #$global_variable"
 end
end
  
# Creating object
class1obj = Class1.new
class1obj.print_global 
  
# Creating another object
class2obj = Class2.new
class2obj.print_global 


Output :

Global variable in Class1 is 10
Global variable in Class2 is 10

In above example, a global variable define whose value is 10. This global variable can be access anywhere in the program.
Example :




# Ruby Program to understand global variable 
$global_variable1 = "GFG"
  
# Defining Class
class Author
  def instance_method
    puts "global vars can be used everywhere. See? #{$global_variable1}, #{$another_global_var}"
  end
  def self.class_method
    $another_global_var = "Welcome to GeeksForGeeks"
    puts "global vars can be used everywhere. See? #{$global_variable1}"
  end
end
  
Author.class_method
# "global vars can be used everywhere. See? GFG"
# => "global vars can be used everywhere. See? GFG"
  
Author = Author.new
Author.instance_method
# "global vars can be used everywhere. See? 
# GFG, Welcome to GeeksForGeeks"
# => "global vars can be used everywhere. See?
# GFG, Welcome to GeeksForGeeks"


Output :

global vars can be used everywhere. See? GFG
global vars can be used everywhere. See? GFG, Welcome to GeeksForGeeks

In above example, We define two global variable in a class. we create a object of class Author than call method.



Last Updated : 25 Sep, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads