Ruby program to implement multiple getter/setter methods using accessors

Ruby Example: Write a program to implement multiple getter/setter methods using accessors.
Submitted by Nidhi, on February 01, 2022

Problem Solution:

In this program, we will implement multiple getters and setters methods using accessors to get/set the value of the instance variables.

Program/Source Code:

The source code to implement the multiple getters/setters method using accessors is given below. The given program is compiled and executed successfully.

# Ruby program to implement multiple getter/setter 
# method using accessors

class Sample
	#constructor
	def initialize(val1,val2)
		@ins_var1 = val1;
		@ins_var2 = val2;
	end
	
	#accessor get/set method
    attr_accessor  :ins_var1
    
    #Getter method of ins_var2
	attr_reader:ins_var2 

end

obj = Sample.new("Hello","Hii");

val1 = obj.ins_var1;
val2 = obj.ins_var2;
print "Value of ins_var11 is: ",val1,"\n";
print "Value of ins_var12 is: ",val2,"\n";

obj.ins_var1 = "Bye";

val1 = obj.ins_var1;
val2 = obj.ins_var2;

print "\n\nValue of ins_var11 is: ",val1,"\n";
print "Value of ins_var12 is: ",val2,"\n";

Output:

Value of ins_var11 is: Hello
Value of ins_var12 is: Hii


Value of ins_var11 is: Bye
Value of ins_var12 is: Hii

Explanation:

In the above program, we created a class Sample. In the Sample class, we implemented constructor and getter, setter methods for multiple instance variables using accessors. Then we created the object of the Sample class with initial values. After that, we used getter/setter methods to get/set the values of ins_var1, ins_var2 variables and print the result.

Ruby Constructors/Destructors, Inheritance Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.