Gurmukh Singh
Gurmukh Singh

Reputation: 2017

Creating an object from a class which is inherited ruby

Im struggling on understanding (after googling) on how to implement this: I have a class:

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

And lets say I have another class which inherits from Student

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

I understand how to build an abject:

student = Student.new(name, age)

How can I build this Student (that I have just created) a Grade object associated with the student and how would I call the inherited object, for example i wanted to:

puts 'student name and associated grade'

I know I can place the grade variable within the Student class, but for the purpose of learning im doing it this way.

Upvotes: 0

Views: 103

Answers (2)

Michael Kohl
Michael Kohl

Reputation: 66837

First off, no need to define accessors in Ruby like that, it's far from idiomatic. Let's clean that up first:

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

Secondly it doesn't seem like Grade should inherit from Student at all, just adjust the latter to also store a Grade instance variable:

class Student
  attr_accessor :name, :age, :grade

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

You can then instantiate a student like this:

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

Or because of the default value you leave off the grade and assign it later:

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

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

This code would do what you wanted:

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}"

Upvotes: 2

Related Questions