Alex Rivera | Logout

How to implement an abstract class in Ruby

Asked 2009-02-04T17:35:43.210
144

I know there is no concept of an abstract class in Ruby. But if it needs to be implemented, how do I go about it? I tried something like this:

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.

Does anyone have any pointers?

Edit
Report

1 Answer

4

If you want to go with an uninstantiable class, in your A.new method, check if self == A before throwing the error.

But really, a module seems more like what you want here. For example, Enumerable is the sort of thing that might be an abstract class in other languages. You technically can't subclass them, but calling include SomeModule achieves roughly the same goal. Is there some reason this won't work for you?

answered 2009-02-04T19:08:03.163

Your Answer