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.
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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer