ADVERTISEMENT
ADVERTISEMENT

Ruby program to implement setter method using 'attr_writer' accessor

Ruby Example: Write a program to implement setter method using 'attr_writer' accessor.
Submitted by Nidhi, on February 01, 2022

Problem Solution:

In this program, we will implement getter and setter methods using "attr_reader", "attr_writer" accessor to get/set the value of the instance variable.

Program/Source Code:

The source code to implement the setter method using the "attr_writer" accessor is given below. The given program is compiled and executed successfully.

# Ruby program to implement setter method using 
# 'attr_writer' accessor

class Sample
	# constructor
	def initialize(val)
		@ins_var = val;
	end
	
	# Getter method
	attr_reader:ins_var 
	
	# accessor set method
    attr_writer :ins_var
end

obj = Sample.new("Hello");

val = obj.ins_var;
print "Value is: ",val,"\n";

obj.ins_var = "Hii";
val = obj.ins_var;
print "Value is: ",val,"\n";

Output:

Value is: Hello
Value is: Hii

Explanation:

In the above program, we created a class Sample.  In the Sample class, we implemented constructor and getter, setter methods using attr_reader, attr_writer accessor. Then we created the object of the Sample class with the initial value. After that, we used getter/setter methods to get/set the value of the ins_var variable and print the result.

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.