从继承ruby的类创建对象

时间:2016-08-01 08:19:49

标签: ruby inheritance

我正在努力理解(谷歌搜索后)如何实现这个:我有一个班级:

class Student
   # constructor method
   def initialize(name,age)
      @name, @age = name, age
   end

   # accessor methods
   def getName
      @name
   end
   def getAge
      @age
   end

   # setter methods
   def setName=(value)
      @name = value
   end
   def setAge=(value)
      @age = value
   end
end

让我说我有另一个继承自学生的课程

class Grade < Student
   #constructor method
   def initialize(grade)
      super
      @grade = grade
   end

   # accessor methods
   def getGrade
      @grade
   end

  # setter methods
   def setGrade=(value)
      @grade = value
   end
end

我理解如何构建一个卑鄙的东西:

student = Student.new(name, age)

如何构建这个Student(我刚刚创建的)与学生关联的Grade对象以及如何调用继承的对象,例如我想:

puts 'student name and associated grade'

我知道我可以将成绩变量放在Student课程中,但是为了学习我这样做。

2 个答案:

答案 0 :(得分:2)

此代码可以满足您的需求:

class Grade
   attr_accessor :value
   def initialize value
     @value = value
   end
end

class Student
   attr_accessor :name, :age, :grade   
   def initialize name, age, grade
      @name, @age, @grade = name, age, Grade.new(grade)
   end
end

st = Student.new 'John', 18, 5
puts "student #{st.name} and associated grade #{st.grade.value}"

答案 1 :(得分:1)

首先,不需要像Ruby那样在Ruby中定义访问器,它远非惯用语。让我们先清理一下:

<h3 my-directive>Hello World!</h3>

其次,似乎class Student attr_accessor :name, :age def initialize(name, age) @name =name @age = age end end class Grade attr_accessor :value def initialize(grade) @value = grade end end 根本不应继承Grade,只需调整后者以存储Student实例变量:

Grade

然后您可以实例化这样的学生:

class Student
  attr_accessor :name, :age, :grade

  def initialize(name, age, grade = nil)
    @name =name
    @age = age
    @grade = grade
  end
end

或者由于默认值,您不在等级中并稍后分配:

student = Student.new("Test", 18, Grade.new(1))