Hunter McMillen Hunter McMillen - 5 months ago 25
Ruby Question

Abstract Method in Ruby

How can I force a subclass to implement a method in Ruby. There doesn't seem to be an abstract keyword in Ruby, which is the approach I would take in Java. Is there another more Ruby-like way to enforce abstract?

Answer

Abstract methods are supposed to be less useful in Ruby because it's not strongly staticly typed.

However, this is what I do:

def AbstractThing
  MESS = "SYSTEM ERROR: method missing"

  def method_one; raise MESS; end
  def method_two; raise MESS; end
end

class ConcreteThing < AbstractThing
  def method_one
     puts "hi"
  end
end

a = ConcreteThing.new
a.method_two # -> raises error.

It rarely seems to be necessary, however.

Comments