2010-02-09 55 views
3

我從來沒有做過任何直接的ruby編碼 - 只能用於Rails框架。描述ruby中的類關係

我不知道如何描述類之間的關係,而不是繼承關係。

例如,一個School對象可能有許多Student對象。 我希望能夠打電話像「myschool.student [2] .first_name」和「mystudent.school.address」

這可能是,我很困惑與關係數據庫的元素的OOP,所以對不起我走了。

回答

9

我不是100%確定是什麼問題在這裏...

對於第一個例子,myschool.students[2].first_name,你的School類需要一個的訪問器字段,它需要是一個數組(或其他支持下標的東西),例如

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類的Studentschool場和address場。

棘手的是,SchoolStudent實例指向彼此,所以你需要在某個時刻設置這些引用。這將是一個簡單的方法:

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

class Student 
    attr_accessor :school 
end 

您仍然需要添加address領域可能還有一些其他的東西,我錯過了,但應該是很容易的事情。

+0

優秀的回覆!我沒有意識到這很簡單。 非常感謝。 – doctororange 2010-02-09 13:12:16

1

通常,在大多數面嚮對象語言中,類成員默認情況下不會暴露於外部世界。即使它是(如在某些語言中),直接訪問班級成員也被認爲是不好的做法。

將成員添加到某個班級(例如,將學生班級添加到學校)時,需要添加訪問者函數以向外部世界提供對這些成員的訪問權限。

這裏的,如果你想了解更多的是一些有用的資源(通過谷歌搜索發現:紅寶石訪問器):

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

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

+0

謝謝。我正在使用attr_accessor來訪問學校和學生的屬性,但我不知道如何告訴程序一所學校有很多學生。 – doctororange 2010-02-09 12:58:45