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

前端 未结 2 1793
小蘑菇
小蘑菇 2021-02-13 00:32

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

相关标签:
2条回答
  • 2021-02-13 00:39

    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/

    0 讨论(0)
  • 2021-02-13 00:51

    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

    0 讨论(0)
提交回复
热议问题