views:

57

answers:

2

I've never done any straight ruby coding - only worked with the Rails framework.

I am not sure how to describe the relationships between Classes, other than inheritance relationships.

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

It may be that I am confusing OOP with elements of relational databasing, so sorry if I'm way off.

+1  A: 

Generally, in most OO languages, class members are not exposed to the outside world by default. Even if it is (as in some languages), it is considered bad practice to directly access class members.

When add members to a class (say, add Student classes to School), you need to add accessor functions to provide the outside world access to those members.

Here's are some useful resources if you want to learn more (found by googling: ruby accessors):

http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/

http://www.rubyist.net/~slagell/ruby/accessors.html

0xfe
Thanks. I am using attr_accessor to access the attributes of both Schools and Students, but I do not know how to tell the program that a school has many students.
doctororange
+3  A: 

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.

liwp
Excellent reply! I didn't realise that it was this simple.Thanks very much.
doctororange