Home »
Ruby Tutorial »
Ruby Programs
Ruby program to access a global variable from a method of the class
Last Updated : December 15, 2025
Problem Solution
In this program, we will create a global variable and access created global variable from the method of a class, and print its value.
Program/Source Code
The source code to access a global variable from a method of the class is given below. The given program is compiled and executed successfully.
# Ruby program to access global variable
# from a method of class
$global_var = 100;
class Sample
def AcessGlobal
print "global_var is: ",$global_var;
end
end
obj = Sample.new();
obj.AcessGlobal();
Output
global_var is: 100
Explanation
In the above program, we created a global variable global_var initialized with 100. Then we created a class Sample that contains a method AccessGlobal(). Here, we accessed the value global variable from the method of a Sample class and printed the value of the global variable.
Ruby Classes & Objects Programs »
Advertisement
Advertisement