ADVERTISEMENT
ADVERTISEMENT

Ruby program to create a class with data members and initialize using initialize() method

Ruby Example: Write a program to create a class with data members and initialize using initialize() method.
Submitted by Nidhi, on December 22, 2021

Problem Solution:

In this program, we will create a class Student that contains 3 data members id, name, and fee. Then we will define the initialize() method to initialize the data members and we will also create a PrintStudentInfo() method to print student information.

Program/Source Code:

The source code to create a class with data members and initialize using initialize() method is given below. The given program is compiled and executed successfully.

# Ruby program to create a class with data members 
# and initialize using initialize() method

class Student
    def initialize(id, name, fee)
        @id   = id;
        @name = name;
        @fee  = fee;    
    end
    
    def PrintStudentInfo()
        print "Student Id:   ",@id,"\n";
        print "Student Name: ",@name,"\n";
        print "Student Fee:  ",@fee,"\n";
    end
end

obj = Student.new(101,"Rahul", 5000);

obj.PrintStudentInfo();

Output:

Student Id:   101
Student Name: Rahul
Student Fee:  5000

Explanation:

In the above program, we created a class called Student. The Student class contains data member's id, name, and fee. Then we defined the initialize() method to initialize the data members and we also created a PrintStudentInfo() method to print student information. Then we created the object of the class and initialized the data members and called PrintStudentInfo() method to print student information.

Ruby Classes & Objects 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.