class Vec2 def _init(x, y) self.x = x self.y = y end def add(other) return Vec2(self.x + other.x, self.y + other.y) end ## Note that operator overloading / friend functions ## haven't implemented at this point (to_string won't actually ## override it). def to_string return "[${self.x}, ${self.y}]" end end v1 = Vec2(1, 2); assert(v1.x == 1 and v1.y == 2) print("v1 = ${v1.to_string()}") v2 = Vec2(3, 4); assert(v2.x == 3 and v2.y == 4) print("v2 = ${v2.to_string()}") v3 = v1.add(v2); assert(v3.x == 4 and v3.y == 6) print("v3 = ${v3.to_string()}") ############################################################################### ## INHERITANCE ############################################################################### class Shape def display() return "${self.name} shape" end end class Circle is Shape def _init(r) self.r = r self.name = "circle" end def area() return 3.14 * self.r * self.r end end class Rectangle is Shape def _init(w, h) self.w = w; self.h = h self.name = "rectangle" end def area() return self.w * self.h end end class Square is Rectangle def _init(w) ## TODO: Currently there is no way of calling super(w, h) ## so we're setting our self here. self.w = w; self.h = w self.name = "square" end end c = Circle(1) assert(c.display() == "circle shape") assert(c is Circle) assert(c is Shape) r = Rectangle(2, 3) assert(r is Shape) assert(r.area() == 6) s = Square(4) assert(s is Square) assert(s is Rectangle) assert(s is Shape) assert(s.area() == 16) print('ALL TESTS PASSED')