Search code examples
rubyclassextendsuperclass

Setting up for an Abstract Super Class in Ruby


I'm very new to this and I try to google it, but I can't seem to really figure out how this really works so I am here asking this question :(...

It's actually quite simple, I just need a syntax of this:

 Class Player <- An abstract super class representing a player object
 Classes Human and Computer <- Classes extending the super class Player

Dat's it! It should be a simple one, you guys can either give me a direct translation of the description into Ruby syntax or some other examples to help me.

One more question just in case, for a abstract super class, is defining a instance method the same as a normal class? Because normal class usually goes like:

def Method1(parameters)
     blah blah blah;
end

Thx in advance!


Solution

  • In Ruby you don't have the keyword abstract to defined abstract classes. If you need to encapsulate functionality that is intended to be shared among different classes, you can extract that into a module, and mix it in with the classes.

    For instance:

    module Player
      # shared functionality
    end
    
    class Human
     include Player
    end
    
    class Computer
      include Player
    end
    

    This works well since abstract, as in disassociated from any specific instance, is just construct that can be achieve in many different ways. Different language choose to be more explicit about it, in ruby is more implicit.