Search⌘ K

Solution: Age of Teacher and Students

Understand how to implement object-oriented programming concepts in Ruby by calculating ages using class inheritance. Learn to extract and average teacher and student ages with methods like collect and inject. Discover practical ways to manage data within Ruby classes and enhance problem-solving skills.

We'll cover the following...

Solution

Ruby 3.1.2
require 'date'
class Person
attr_accessor :name, :birth_date
def initialize(name, b_date)
@name = name
@birth_date = Date.parse(b_date)
end
def age
if @birth_date
tmp_year = Date.today.year - @birth_date.year
tmp_month = Date.today.month - @birth_date.month
tmp_day = Date.today.day - @birth_date.day
return tmp_year - 1 if (tmp_month < 0) || (tmp_month == 0 && tmp_day < 0)
return tmp_year
else
nil
end
end
end
class Teacher < Person
end
class Student < Person
attr_accessor :grade
def initialize(name, b_date, grade)
super(name, b_date)
@grade = grade
end
end
def teacher_avg_age(teachers)
return teachers.collect{ |y| y.age }.inject(0.0){ |result, el| result + el } / teachers.length
end
def student_avg_age(students, grade)
grade_students = []
students.each do |x|
grade_students << x if x.grade == grade
end
students_count = grade_students.size
average_grade_age = grade_students.collect{ |y| y.age }.inject(0.0) { |result, el| result + el } / students_count
return 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 ...