Age of Teacher and Students
Learn about inheritance, method overriding, and instance variables in Ruby and apply these concepts to solve a problem.
We'll cover the following...
Problem
A school consists of teachers and students, and students are grouped by grades. Implement the Teacher and Student classes with age method to calculate the age from the date of birth. Use the concept of inheritance to improve code reusability.
Also, write the following methods:
teacher_avg_agethat takes an array of teacher objects and returns their average age.student_avg_agethat takes two parameters—an array of student objects and a grade—and returns the average age of students grouped by the specified grade.
Input data
teachers = []teachers << Teacher.new("James Bond", "1978-04-03") # name, birthdayteachers << Teacher.new("Michael Zasky", "1988-01-02")students = []students << Student.new("John Sully", "2009-10-03", 10) # grade 10students << Student.new("Michael Page", "2009-05-07", 11)students << Student.new("Mike Mills", "2005-06-30", 11)students << Student.new("Anna Boyle", "2008-12-03", 10)students << Student.new("Dominic Chan", "2009-09-10", 10)
Output
Assuming the program is executed on the date 2022-07-22, then it should display the following output:
Teacher 'James Bond' age: 43Average Teacher age: 38.5Average grade-10 students age: 12.33
Purpose
Instance variables
Read and write instance variables
Class constructor
Class inheritance
Age calculation
Use of array operations (review)
Analyze
The core function is to calculate ages, and we have two classes,
TeacherandStudent(identified from the code fragment above). We could write twoagefunctions in both theTeacherandStudentclasses. However, this is redundant. We wouldn’t want to write anotheragemethod to support ...