Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract Method in Ruby

Tags:

ruby

abstract

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?

like image 736
Hunter McMillen Avatar asked Jul 22 '11 15:07

Hunter McMillen


2 Answers

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

However, this is what I do:

class 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.

like image 187
Andy Avatar answered Oct 10 '22 05:10

Andy


I like the answer by pvandenberk, but I would improve it as follows:

module Canine      # in Ruby, abstract classes are known as modules   def bark     fail NotImplementedError, "A canine class must be able to #bark!"   end end 

Now if you make a class belonging to Canine "abstract class" (ie. a class that has Canine module in its ancestors), it will complain if it is found that #bark method is not implemented:

class Dog   include Canine   # make dog belong to Canine "abstract class" end  Dog.new.bark       # complains about #bark not being implemented  class Dog   def bark; "Bow wow!" end end  # Now it's OK: Dog.new.bark #=> "Bow wow!" 

Note that since Ruby classes are not static, but always open to changes, Dog class itself cannot enforce existence of #bark methods, since it doesn't know when is it supposed to be finished. If you as a programmer do, it is up to you to test it at such time.

like image 30
Boris Stitnicky Avatar answered Oct 10 '22 07:10

Boris Stitnicky