How to implement an abstract class in ruby?

Chirantan picture Chirantan · Feb 4, 2009 · Viewed 93.1k times · Source

I know there is no concept of abstract class in ruby. But if at all it needs to be implemented, how to go about it? I tried something like...

class A
  def self.new
    raise 'Doh! You are trying to write Java in Ruby!'
  end
end

class B < A
  ...
  ...
end

But when I try to instantiate B, it is internally going to call A.new which is going to raise the exception.

Also, modules cannot be instantiated but they cannot be inherited too. making the new method private will also not work. Any pointers?

Answer

Dan Rosenstark picture Dan Rosenstark · Mar 23, 2010

Just to chime in late here, I think that there's no reason to stop somebody from instantiating the abstract class, especially because they can add methods to it on the fly.

Duck-typing languages, like Ruby, use the presence/absence or behavior of methods at runtime to determine whether they should be called or not. Therefore your question, as it applies to an abstract method, makes sense

def get_db_name
   raise 'this method should be overriden and return the db name'
end

and that should be about the end of the story. The only reason to use abstract classes in Java is to insist that certain methods get "filled-in" while others have their behavior in the abstract class. In a duck-typing language, the focus is on methods, not on classes/types, so you should move your worries to that level.

In your question, you're basically trying to recreate the abstract keyword from Java, which is a code-smell for doing Java in Ruby.