Description of class relationships in ruby

I have never done direct ruby ​​coding - it only worked with the Rails framework.

I am not sure how to describe relations between classes other than inheritance relations.

For example, a School object can have many Student objects. I would like to be able to make calls like "myschool.student [2] .first_name" and "mystudent.school.address"

I might be confusing OOP with relational database items, so sorry if I leave.

+3
source share
2 answers

I am not 100% sure that the question is here ...

myschool.students[2].first_name School students, ( - , ), .

class School
  attr_reader :students

  def initialize()
    @students = []
  end
end

myschool.students[2] -. , students Student, :

class Student
  attr_reader :first_name, :last_name

  def initialize(first, last)
    @first_name = first
    @last_name = last
  end
end

myschool.students[2].first_name .

mystudent.school.address School Student <<212 > School.

, School Student , - . :

class School
  def add_student(student)
    @students << student
    student.school = self
  end
end

class Student
  attr_accessor :school
end

address , , , , .

+9

Source: https://habr.com/ru/post/1732020/


All Articles