polymorphism.sf 807 B

123456789101112131415161718192021222324252627282930313233343536
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Polymorphism
  4. #
  5. class Point(x=0, y=0) {
  6. }
  7. class Circle(x=0, y=0, r=0) {
  8. }
  9. func pp(Point obj) {
  10. say "Point at #{obj.x},#{obj.y}";
  11. }
  12. func pp(Circle obj) {
  13. say "Circle at #{obj.x},#{obj.y} with radius #{obj.r}";
  14. }
  15. pp(Point.new); # => Point at 0,0
  16. var p = Point.new(1, 2); # create a point
  17. pp(p); # => Point at 1,2
  18. say p.x; # => 1
  19. p.y += 1; # add one to y
  20. pp(p); # => Point at 1,3
  21. var c = Circle.new(4,5,6); # create a circle
  22. var d = c.clone; # clone it
  23. d.r = 7.5; # and change the radius to 7.5
  24. pp(c); # => Circle at 4,5 with radius 6
  25. pp(d); # => Circle at 4,5 with radius 7.5