 
 This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.
| Creating an Abstract Method | ||
|---|---|---|
| Code | Expected | Actual | 
| class Shape2D
  def area
    raise NotImplementedError.
      new("#{self.class.name}#area is an abstract method.")
  end
end
Shape2D.new.area | NotImplementedError: Shape2D#area is an abstract method. ... | NotImplementedError: Shape2D#area is an abstract method. from (irb):4:in `area' from (irb):7 | 
| class Square < Shape2D
  def initialize(length)
    @length = length
  end
  def area
    @length ** 2
  end
end
Square.new(10).area | 100 | 100 | 
| class Shape2D
  def initialize
    raise NotImplementedError.
      new("#{self.class.name} is an abstract class.")
  end
end
Shape2D.new | NotImplementedError: Shape2D is an abstract class. ... | NotImplementedError: Shape2D is an abstract class. from (irb):20:in `initialize' from (irb):23 | 
| class Class
  def abstract(*args)
    args.each do |method_name|
      define_method(method_name) do |*args|
        if method_name == :initialize
          msg = "#{self.class.name} is an abstract class."
        else
          msg = "#{self.class.name}##{method_name} is an abstract method."
        end
        raise NotImplementedError.new(msg)
     end
    end
  end
end
class Animal
  abstract :initialize, :move
end
Animal.new | NotImplementedError: Animal is an abstract class. ... | NotImplementedError: Animal is an abstract class. from (irb):33:in `initialize' from (irb):41 | 
| class Sponge < Animal
  def initialize
    @type = :Sponge
  end
end
sponge = Sponge.new
sponge.move | NotImplementedError: Sponge#move is an abstract method. ... | NotImplementedError: Sponge#move is an abstract method. from (irb):33:in `move' from (irb):48 | 
| class Cheetah < Animal
  def initialize
    @type = :Cheetah
  end
  def move
    "Running!"
  end
end
Cheetah.new.move | "Running!" | "Running!" | 
| class Sponge
  def move
    "Floating on ocean currents!"
  end
end
sponge.move | "Floating on ocean currents!" | "Floating on ocean currents!" |