”接口与Ruby 中不必要的抽象类” -->有人可以解释一下吗?
我正在尝试了解 Ruby,但我遇到的一件事是缺乏接口/抽象类支持。通过谷歌搜索,我不断看到与抽象类相关的 Ruby 问题的回答是“你在 Java 中思考。Ruby 不是那样工作的”
那么,如果没有接口/抽象类,如何在 Ruby 中工作呢?
例如,在 Java 中,我可能会创建一个抽象类“book”,其子类为“novel”、“textbook”和“journal”。我在“书”中添加了很多常见功能,但我不希望它可以直接访问 - 书必须是小说、教科书或期刊。
在 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"
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我也是 Ruby 入门者。根据我的理解,Ruby 中的抽象类有一个更接近的竞争对手。这就是
模块
。您无法创建模块的任何实例,但可以包含在另一个类中。因此,目标类将获得父类的全部功能。在 java/C# 等静态类型语言中,接口强制类在编译时拥有所有方法。由于 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 parentIn 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..
Cheers
有很多方法可以实现这种类型的东西,包括abstract_type gem。虽然 ruby 不需要它并且有 mixins,但我认为在某些情况下,例如适配器,您希望使用更明确的东西来保护一组对象的接口。
另外,请查看 http://metabates。 com/2011/02/07/building-interfaces-and-abstract-classes-in-ruby/
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/