RbRuby
IntermediateLesson 10 of 16

Classes & Objects – Ruby

Attributes, constructor, inheritance, visibility and comparisons.

You define a class with class. initialize is the constructor, @name an instance variable, attr_reader/attr_accessor create getters/setters. puts automatically calls to_s. @@x are class variables, self.method are class methods.

class Konto
  WAEHRUNG = "EUR"
  @@anzahl = 0

  attr_reader :inhaber, :saldo

  def initialize(inhaber, saldo = 0)
    @inhaber = inhaber
    @saldo = saldo
    @@anzahl += 1
  end

  def einzahlen(betrag)
    raise ArgumentError, "Amount must be positive" unless betrag.positive?
    @saldo += betrag
    self                  # enables chaining
  end

  def self.anzahl
    @@anzahl
  end

  def to_s
    format("%s: %.2f %s", @inhaber, @saldo, WAEHRUNG)
  end
end

k = Konto.new("Ada").einzahlen(50).einzahlen(25.5)
puts k                 # Ada: 75.50 EUR
puts Konto.anzahl      # 1

With < you inherit, super calls the method of the parent class. Methods under private can only be called internally.

class Tier
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def sprich
    "#{name} makes a sound"
  end

  def vorstellen
    "I am #{name}. #{laut}"
  end

  private

  def laut
    sprich.upcase
  end
end

class Hund < Tier
  def initialize(name, rasse)
    super(name)
    @rasse = rasse
  end

  def sprich
    "#{name} says Woof!"
  end
end

hund = Hund.new("Rex", "Collie")
puts hund.vorstellen        # I am Rex. REX SAYS WOOF!
begin
  hund.laut
rescue NoMethodError => e
  puts "private method: #{e.class}"
end
puts hund.is_a?(Tier), Hund.superclass, Hund.ancestors.first(2).inspect   # true, Tier, [Hund, Tier]

You customize equality and debug output with ==, hash/eql? and inspect:

class Punkt
  attr_reader :x, :y

  def initialize(x, y)
    @x, @y = x, y
  end

  def ==(other)
    other.is_a?(Punkt) && x == other.x && y == other.y
  end
  alias eql? ==

  def hash
    [x, y].hash
  end

  def to_s = "(#{x}, #{y})"
  def inspect = "#<Punkt #{self}>"
end

puts Punkt.new(1, 2) == Punkt.new(1, 2)              # true
p Punkt.new(1, 2)                                    # #<Punkt (1, 2)>
puts({ Punkt.new(1, 2) => "A" }[Punkt.new(1, 2)])    # A
WarningRuby has no truly "private fields" from the outside: instance_variable_get(:@saldo) reads it anyway. private only prevents the normal method call with an explicit receiver. And attr_accessor opens write access – prefer attr_reader if nobody from outside should change it.
TipRuby has only single inheritance. You share reusable behavior via modules (mixins). Classes are objects themselves and are open for extension at any time (class String ... end).