Ruby classes and inheritance


 
class Person
  def initialize(name, date_birth)
    @name = name
    @date_birth = date_birth
  end
  
  def to_s
    "Person #{@name} born on #{@date_birth}"
  end
  
# standard methods that create "getters" for instance variables
  attr_reader :name, :date_birth
end

carol = Person.new("Carol Smith","1970-3-15")
puts carol

puts carol.class
puts carol.class.superclass

puts carol.instance_of?(Person)
puts carol.instance_of?(Object)

dave = Person.new("David Brown", "1976-11-23")
puts dave

# can do it because of the attribute reader
puts carol.name

puts carol.object_id
puts dave.object_id

#puts carol.methods.sort # all methods, including those inherited from Object

# adding a method to check if this person is older than another
# person
class Person
  def older another
    return @date_birth < another.date_birth
  end
end

puts carol.older(dave)
puts dave.older(carol)

# definiing "setters" for methods
class Person
  attr_writer :name
  # or you can define it like this: 
  #def name=(newname)
  #  @name = newname
  #end
end

carol.name = "Carole Smith"
puts carol

# no more changes to an object
carol.freeze
# cannot modify an object:
#carol.name = "Hillary Clinton"

dave.name = "Cool Dave"
puts dave
dave.name = "David Brown"

# an error: no such method
#carol.do_something

# make a class react to a call to an unknown method
class Person 
  def method_missing(m)
    puts "no method #{m} here"
  end
end
carol.do_something

###### Inheritance ####################

class Student < Person
  # initializer is optional, by default the one in superclass
  # is called  
  def initialize(name, date_birth, gpa)
    super(name, date_birth)
    @gpa = gpa
  end
  attr_reader :gpa
  # overriding to_s
  def to_s
    super + " has gpa of #{@gpa}"
  end
end

sam = Student.new("Sam Student", "1989-5-20", 3.45)
puts sam

puts sam.older(carol)
puts carol.older(sam)

CSci 4651 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.