An example of writing ruby classes


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


# You can add methods to a class at any point

# 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.to_s

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

The output


Person Carol Smith born on 1970-3-15
Person
Object
true
false
Person David Brown born on 1976-11-23
Carol Smith
73161200
73161090
true
false
Person Carole Smith born on 1970-3-15
Person Cool Dave born on 1976-11-23
no method do_something here
Person Sam Student born on 1989-5-20 has gpa of 3.45
false
true

UMM CSci 4657

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.