Ruby program to implement getter method using 'attr_reader' accessor

Ruby Example: Write a program to implement getter method using "attr_reader" accessor.
Submitted by Nidhi, on January 28, 2022

Problem Solution:

In this program, we will implement the getter method using the "attr_reader" accessor to get the value of the instance variable.

Program/Source Code:

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

# Ruby program to implement getter method using 
# 'attr_reader' accessor

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

obj = Sample.new("Hello");

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

Output:

Value is: Hello

Explanation:

In the above program, we created a class Sample.  In the Sample class, we implemented the constructor and getter method using the "attr_reader" accessor. Then we created the object of the Sample class with the initial value. After that, we got the value of the ins_var variable and print the result.

Ruby Constructors/Destructors, Inheritance Programs »




Comments and Discussions!

Load comments ↻





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