Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Interfaces & Abstract Classes unnecessary in Ruby" --> Can someone explain?

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?

like image 644
PlankTon Avatar asked Feb 22 '11 10:02

PlankTon


2 Answers

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

like image 171
RameshVel Avatar answered Oct 15 '22 01:10

RameshVel


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/

like image 40
ron pastore Avatar answered Oct 14 '22 23:10

ron pastore