ADVERTISEMENT
ADVERTISEMENT

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

Ruby Example: Write a program to access a global variable from a method of the class.
Submitted by Nidhi, on December 22, 2021

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


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.