I'm not 100% sure what the question is here...
For the first example, myschool.students[2].first_name
, your School
class needs an accessor for a students
field, which needs to be an array (or something else that supports subscripts) e.g.
class School
attr_reader :students
def initialize()
@students = []
end
end
The above allows myschool.students[2]
to return something. Assuming that students
contains instances of a Student
class, that class might be something like this:
class Student
attr_reader :first_name, :last_name
def initialize(first, last)
@first_name = first
@last_name = last
end
end
Now your example, myschool.students[2].first_name
, should work.
For the second example, mystudent.school.address
, you need to have a school
field in the Student
class and an address
field in the School
class.
The tricky bit is that the School
and Student
instances point to each other, so you need to set up those references at some point. This would be a simple way:
class School
def add_student(student)
@students << student
student.school = self
end
end
class Student
attr_accessor :school
end
You still need to add the address
field and possibly some other stuff that I missed, but that should be easy enough to do.