ADVERTISEMENT
ADVERTISEMENT

Ruby program to implement getter and setter methods

Ruby Example: Write a program to implement getter and setter methods.
Submitted by Nidhi, on January 28, 2022

Problem Solution:

In this program, we will implement a getter and methods to get and set the value of the instance variable and print it.

Program/Source Code:

The source code to implement getter and setter methods is given below. The given program is compiled and executed successfully.

# Ruby program to implement 
# getter and setter methods

class Sample
	#constructor
	def initialize(val)
		@ins_var = val;
	end
	
	#Getter method
	def GetVal
		@ins_var;
	end
	
	def SetVal=(val)
        @ins_var = val;
    end
  
end

obj = Sample.new("Hello");

val = obj.GetVal();
print "Value is: ",val,"\n";

obj.SetVal = "Hiii";
val = obj.GetVal();
print "Value is: ",val,"\n";

Output:

Value is: Hello
Value is: Hiii

Explanation:

In the above program, we created a class Sample. The Sample class contains constructor, getter method GetVal(), and setter method SetVal(). We assigned the value of the instance variable using the constructor and SetVal() method. After that, we created the object of the Sample class and used the getter and setter method to get/set the value of the ins_var variable.

Ruby Constructors/Destructors, Inheritance Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



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.