Q:

Ruby program to implement getter/setter method using \'attr_accessor\' accessor

0

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

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 implement setter using "attr_accessor" accessor is given below. The given program is compiled and executed successfully.

# Ruby program to implement getter/setter method using 
# 'attr_accessor' accessor

class Sample
	#constructor
	def initialize(val)
		@ins_var = val;
	end
	
	#accessor get/set method
    attr_accessor  :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_accessor 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.

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

total answers (1)

Ruby program to implement multiple getter/setter m... >>
<< Ruby program to implement setter method using \�...