...

/

Age of Teacher and Students

Age of Teacher and Students

Learn about inheritance, method overriding, and instance variables in Ruby and apply these concepts to solve a problem.

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_age that takes an array of teacher objects and returns their average age.

  • student_avg_age that 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, birthday
teachers << Teacher.new("Michael Zasky", "1988-01-02")
students = []
students << Student.new("John Sully", "2009-10-03", 10) # grade 10
students << 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)
Sample data values to calculate individual age and the average age of teachers and students

Output

Assuming the program is executed on the date 2022-07-22, then it should display the following output:

Teacher 'James Bond' age: 43
Average Teacher age: 38.5
Average grade-10 students age: 12.33
Sample output against the sample data values

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, Teacher and Student (identified from the code fragment above). We could write two age functions in both the Teacher and Student classes. However, this is redundant. We wouldn’t want to write another age method to support ...