Q:

Ruby program to access a global variable from a method of the class

0

In this program, we will create a global variable and access created global variable from the method of a class, and print its value.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now