19

I'm trying to wrap my head around Ruby, and one thing I'm struggling with is the lack of interface/abstract class support. From googling about, the response I continuously see to abstract class related Ruby questions is "You're thinking in Java. Ruby doesn't work that way"

So, how would one work in Ruby without interfaces/abstract classes?

For example, in Java I might create an abstract class "book", with subclasses "novel", "textbook", and "journal". There is a lot of common functionality that I throw in 'book', but I don't want it to be directly accessible - a book must be either a novel, textbook or journal.

In ruby, how would I write out that sort of functionality?

PlankTon
  • 12,443
  • 16
  • 84
  • 153

2 Answers2

18

I am also Ruby starter. From my understanding, there is a closer rival for abstract classes in ruby. that is module. you can't create any instances of module but you can include with another class. So a target class will get the whole functionality of parent

  module Log
    def write
      //blah
    end
  end

  class EventLog
    include Log

    def Prepare
    end
  end

In statically typed languages like java/C# , Interfaces enforce the classes to have all the methods at compile time. Since Ruby is dynamic, there is no meaning in it.

For more clarity, check these posts why dynamic languages don't require interfaces..

  1. why-dont-we-require-interfaces-in-dynamic-languages
  2. why-do-dynamic-languages-like-ruby-and-python-not-have-the-concept-of-interfaces

Cheers

Community
  • 1
  • 1
RameshVel
  • 64,778
  • 30
  • 169
  • 213
  • 6
    These are called mixins (edit: one type of mixin, in this case `include` affects instance methods, while you can also use `extend` which will affect class methods… hopefully I explained that correctly), if I remember right. Essentially, the module provides functionality that to be shared among a number of classes, but is not itself a class. In doing this, you cannot instantiate a Book module, but you can instantiate a Journal class that includes the Book module. –  Feb 22 '11 at 10:53
1

there are ways to implement this type of thing, including abstract_type gem. While ruby doesn't require it and has mixins, i think there are cases, like adapters, where you'd want to secure your interface to a set of objects with something more explicit.

also, check out http://metabates.com/2011/02/07/building-interfaces-and-abstract-classes-in-ruby/

ron pastore
  • 270
  • 2
  • 6