ADVERTISEMENT
ADVERTISEMENT

Ruby program to initialize instance variables using the constructor

Ruby Example: Write a program to initialize instance variables using the constructor.
Submitted by Nidhi, on January 28, 2022

Problem Solution:

In this program, we will initialize instance variables using the constructor and print the value of created variables in the show() method.

Program/Source Code:

The source code to initialize instance variables using the constructor is given below. The given program is compiled and executed successfully.

# Ruby program to initialize instance variable 
# using constructor

class Sample
	def initialize
		@ins_var1 = "ABC";
		@ins_var2 = "XYZ";
	end
	
	def show
		print "ins_var1: ",@ins_var1,"\n";
		print "ins_var2: ",@ins_var2,"\n";
	end
end

obj = Sample.new();
obj.show();

Output:

ins_var1: ABC
ins_var2: XYZ

Explanation:

In the above program, we created a class Sample. The Sample class contains the constructor and show() method. We initialized the instance variables ins_var1, ins_var2 in the constructor and printed them inside the show() class.

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.