Object-Oriented Ruby

Virtual Constructor
You can run into trouble inheriting from a class containing a method that creates a new instance of the class. This section describes a solution to this problem.

Let's say you want to create a Number class with an overloaded addition operator

class Number attr_reader :x def initialize(x) @x = x end def +(o) Number.new(@x + o.x) end def to_s "the Number #{@x}" end end

If you inherit from it

class FancyNumber < Number def to_s "the FancyNumber #{@x}" end end

the addition operator won't return a FancyNumber, but a Number. It can be solved with this trick

class Number attr_reader :x def initialize(x) @x = x end def +(o) self.class.new(@x + o.x) end <- create a new instance of      def to_s "the Number #{@x}" end         'this class' end

Mixins
This is just a small example of a mixin, the Ruby answer to multiple inheritance / interfaces

module Info # mixin def showHp puts "* HIT POINTS: #{@hp}" end end class Creature include Info def initialize(hp) @hp = hp end end class Hero include Info def initialize(str, hp) @str, @hp = str, hp end end orc = Creature.new(100) knight = Hero.new(40, 70) orc.showHp knight.showHp

it outputs

* HIT POINTS: 100 * HIT POINTS: 70