Ruby 中的抽象方法 [英] Abstract Method in Ruby

查看:26
本文介绍了Ruby 中的抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何强制子类在 Ruby 中实现方法.Ruby 中似乎没有抽象关键字,这是我在 Java 中采用的方法.还有另一种更像 Ruby 的方式来强制抽象吗?

How can I force a subclass to implement a method in Ruby. There doesn't seem to be an abstract keyword in Ruby, which is the approach I would take in Java. Is there another more Ruby-like way to enforce abstract?

推荐答案

抽象方法在 Ruby 中应该不太有用,因为它不是 strong 静态类型的.

Abstract methods are supposed to be less useful in Ruby because it's not strongly staticly typed.

然而,这就是我所做的:

However, this is what I do:

class AbstractThing
  MESS = "SYSTEM ERROR: method missing"

  def method_one; raise MESS; end
  def method_two; raise MESS; end
end

class ConcreteThing < AbstractThing
  def method_one
     puts "hi"
  end
end

a = ConcreteThing.new
a.method_two # -> raises error.

不过,这似乎很少有必要.

It rarely seems to be necessary, however.

这篇关于Ruby 中的抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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