Ruby

Contributed by Chris Rathman

Shape class (Shape.rb)

class Shape
   attr :x
   attr :y

   # constructor
   def initialize(initx, inity)
      setX(initx)
      setY(inity)
   end

   # get the x & y components for the object
   def getX
      return @x
   end
   def getY
      return @y
   end

   # set the x & y components for the object
   def setX(newx)
      @x = newx
   end
   def setY(newy)
      @y = newy
   end

   # move the x & y position of the object
   def moveTo(newx, newy)
      setX(newx)
      setY(newy)
   end
   def rMoveTo(newx, newy)
      moveTo(newx + getX, newy + getY)
   end
end

Rectangle class (Rectangle.rb)

require "Shape.rb"

class Rectangle < Shape
   attr :width
   attr :height

   # constructor
   def initialize(initx, inity, initwidth, initheight)
      super(initx, inity)
      setWidth(initwidth)
      setHeight(initheight)
   end

   # get the width & height of the object
   def getWidth
      return @Width
   end
   def getHeight
      return @Height
   end

   # set the width & height of the object
   def setWidth(newwidth)
      @width = newwidth
   end
   def setHeight(newheight)
      @height = newheight
   end

   # draw the rectangle
   def draw
      print("Drawing a Rectangle at:(", @x, ",", @y,
         "), width ", @width, ", height ", @height, "\n")
   end
end

Circle class (Circle.rb)

require "Shape.rb"

class Circle < Shape
   attr :radius

   # constructor
   def initialize(initx, inity, initradius)
      super(initx, inity)
      setRadius(initradius)
   end

   # get the radius of the object
   def getRadius
      return @radius
   end

   # set the radius of the object
   def setRadius(newradius)
      @radius = newradius
   end

   # draw the circle
   def draw
      print("Draw a Circle at:(", @x, ",", @y,
         "), radius ", @radius, "\n")
   end
end

Polymorphism test (Polymorph.rb)

require "Rectangle.rb"
require "Circle.rb"

# create a collection containing various shape instances
scribble = [Rectangle.new(10, 20, 5, 6), Circle.new(15, 25, 8)]

# iterate through the collection and handle shapes polymorphically
scribble.each do |ashape|
   ashape.draw
   ashape.rMoveTo(100, 100)
   ashape.draw
end

# access a rectangle specific function
arectangle = Rectangle.new(0, 0, 15, 15)
arectangle.setWidth(30)
arectangle.draw

Output

Drawing a Rectangle at:(10,20), width 5, height 6
Drawing a Rectangle at:(110,120), width 5, height 6
Draw a Circle at:(15,25), radius 8
Draw a Circle at:(115,125), radius 8
Drawing a Rectangle at:(0,0), width 30, height 15

Chris Rathman / Chris.Rathman@tx.rr.com