Abstract Methods in Ruby

In order to create an abstract method of a class and let its subclass to fill in the blanks, you need to raise a NotImplementedError: as shown in the example below.

class MyClass
 def my_method
  raise NotImplementedError: new(“#{self.class.name} > my_method is not implemented”
 end
end

class MySubclass < MyClass
 def initialize(my_arg)
  @my_arg = my_arg
end

 def my_method
  @my_arg*2
 end
end

Ruby does not have built in abstract methods or classes the same way Java or C# have and does not enforce abstractedness the same way. So, NotImplementedError is kind of work around to provide you with the abstractedness that you may need. Moreover, Ruby is so relaxed that it will allow to instantiate class with only abstract methods and you’ll only be able to figure out it is an abstract or not by running into NotImplementedError message.

One way to deal with this lax of rules is to raise NotImplementedError message from within initialize method.

Another way of defining an abstract class is as follows

class MyClass
 abstract :initialize, :my_method
end

class MySubclass < MyClass
 def initialize
  @type = :my_value
 end
end

Be mindful that we only implemented initialize method and my_method is still an abstract method of our class. 

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…