Solution: Age of Teacher and Students
Solidify your understanding of inheritance by reviewing the solution to this problem.
We'll cover the following...
Solution
Press + to interact
require 'date'class Personattr_accessor :name, :birth_datedef initialize(name, b_date)@name = name@birth_date = Date.parse(b_date)enddef ageif @birth_datetmp_year = Date.today.year - @birth_date.yeartmp_month = Date.today.month - @birth_date.monthtmp_day = Date.today.day - @birth_date.dayreturn tmp_year - 1 if (tmp_month < 0) || (tmp_month == 0 && tmp_day < 0)return tmp_yearelsenilendendendclass Teacher < Personendclass Student < Personattr_accessor :gradedef initialize(name, b_date, grade)super(name, b_date)@grade = gradeendenddef teacher_avg_age(teachers)return teachers.collect{ |y| y.age }.inject(0.0){ |result, el| result + el } / teachers.lengthenddef student_avg_age(students, grade)grade_students = []students.each do |x|grade_students << x if x.grade == gradeendstudents_count = grade_students.sizeaverage_grade_age = grade_students.collect{ |y| y.age }.inject(0.0) { |result, el| result + el } / students_countreturn average_grade_age.round(2)end
Explanation
Lines 11–21: The
age
method calculates age by finding the difference among the year, month, and day of the instance variable ...