“Interfaces& amp; Ruby中不必要的抽象类“ - >谁能解释一下? [英] "Interfaces & Abstract Classes unnecessary in Ruby" --> Can someone explain?

查看:114
本文介绍了“Interfaces& amp; Ruby中不必要的抽象类“ - >谁能解释一下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图绕过Ruby,而我正在努力的一件事是缺乏接口/抽象类支持。从谷歌搜索,我不断看到抽象类相关的Ruby问题的响应是你在用Java思考.Ruby不能这样工作

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"

那么,如何如果没有接口/抽象类,Ruby会工作吗?

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

例如,在Java中,我可能创建一个抽象类book,子类为novel,textbook和期刊。我在书中提到了许多常见的功能,但我不希望它可以直接访问 - 一本书必须是小说,教科书或期刊。

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.

在ruby中,我该如何写出那种功能?

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

推荐答案

我也是Ruby的首发。根据我的理解,红宝石中的抽象类更接近竞争对手。那是模块。你不能创建任何模块实例,但你可以包含另一个类。所以目标类将获得父的全部功能

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

在java / C#这样的静态类型语言中,Interfaces强制这些类在编译时拥有所有方法。由于Ruby是动态的,因此没有任何意义。

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. 为什么 - 我们不要求界面动态语言

  2. 为什么-DO动态语言样红宝石和Python的 - 不具有最concept-接口

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

干杯

这篇关于“Interfaces& amp; Ruby中不必要的抽象类“ - >谁能解释一下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆