- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" end end # Defining second Class class SecondClass def print_global_variable puts "Global variable in SecondClass is #$global_var" end end # Creating object firstclassobj = FirstClass.new firstclassobj.print_global_variable # Creating another object secondclassobj = SecondClass.new secondclassobj.print_global_variable
Output
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}" end def self.class_method $some_global_var = "Welcome to TutorialsPoint" puts "Available? #{$global_var}" end end Teacher.class_method
Output
Available? Tutorial
- Related Articles
- How to Use Instance Variables in Ruby
- How to use Global Variables in JavaScript?
- How to minimize the use of global variables in JavaScript?
- How to declare global variables in Android?
- How to declare global Variables in JavaScript?
- How to use the Properties file to declare global variables in a framework in Selenium?
- How to use BigDecimal in Ruby?
- How to clear the global variables in Postman?
- Global variables in Java
- How and why to avoid global variables in JavaScript?
- How to use the "defined?" keyword in Ruby?
- How to use the "not" keyword in Ruby?
- How to use the "or" keyword in Ruby?
- Global Scope Variables in Postman?
- Global Variables in Lua Programming

Advertisements