【问题标题】:Describing class relationships in ruby在 ruby​​ 中描述类关系
【发布时间】:2011-01-14 19:15:53
【问题描述】:

我从未做过任何直接的 ruby​​ 编码 - 只使用 Rails 框架。

除了继承关系,我不知道如何描述类之间的关系。

例如,一个 School 对象可能有许多 Student 对象。 我希望能够拨打“myschool.student[2].first_name”和“mystudent.school.address”之类的电话

这可能是我将 OOP 与关系数据库的元素混淆了,如果我说错了,很抱歉。

【问题讨论】:

    标签: ruby oop class object


    【解决方案1】:

    我不是 100% 确定这里的问题是什么......

    对于第一个示例 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,您需要在Student 类中有一个school 字段,在School 类中有一个address 字段。

    棘手的一点是SchoolStudent 实例相互指向,因此您需要在某个时候设置这些引用。这将是一个简单的方法:

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

    您仍然需要添加 address 字段以及可能我错过的其他一些内容,但这应该很容易做到。

    【讨论】:

    • 很好的回复!我没有意识到它是如此简单。非常感谢。
    【解决方案2】:

    一般来说,在大多数 OO 语言中,类成员默认情况下是不暴露给外界的。即使是(如在某些语言中),直接访问类成员也被认为是不好的做法。

    当向班级添加成员时(例如,向 School 添加 Student 班级),您需要添加 访问器函数以提供对这些成员的外部访问权限。

    如果您想了解更多信息,这里有一些有用的资源(通过谷歌搜索找到:ruby accessors):

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

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

    【讨论】:

    • 谢谢。我正在使用 attr_accessor 访问 Schools 和 Students 的属性,但我不知道如何告诉程序一个学校有很多学生。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    相关资源
    最近更新 更多