Contributed by Guy N. Hurst
After putting together this comparison, Guy Hurst sent me the following note.
Here is Guy's improved version.
I found your page at http://onestepback.org/oostuff/ to be very interesting.
I have been working with ruby lately, and looked at that version. I realized that I could suggest a shorter version (much shorter) to the provided ruby script.
Basically, by using 'attr_accessor :var' instead of 'attr :var', one can get or set the var using 'instance.var' or 'instance.var=xxx' and dispense with defining/using getVar() or setVar() methods.
class Shape attr_accessor :x, :y # constructor def initialize(initx, inity) @x=initx @y=inity end # move the x & y position of the object def moveTo(newx, newy) @x=newx @y=newy end def rMoveTo(newx, newy) moveTo(newx + @x, newy + @y) end end
require "Shape.rb" class Rectangle < Shape attr_accessor :width, :height # constructor def initialize(initx, inity, initwidth, initheight) super(initx, inity) @width=initwidth @height=initheight end # draw the rectangle def draw print("Drawing a Rectangle at:(", @x, ",", @y, "), width ", @width, ", height ", @height, "\n") end end
require "Shape.rb" class Circle < Shape attr_accessor :radius # constructor def initialize(initx, inity, initradius) super(initx, inity) @radius=initradius end # draw the circle def draw print("Draw a Circle at:(", @x, ",", @y, "), radius ", @radius, "\n") end end
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.width=30 arectangle.draw