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

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

问题描述

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

解决方案

在Ruby中,抽象方法应该不太有用,因为它不是静态地 strong 。 / p>

但是,这是我的工作

  class AbstractThing 
MESS =系统错误:方法丢失

def method_one;提高MESS; end
def method_two;提高MESS;结束
结束

类ConcreteThing< Abstractthing
def method_one
放置 hi
结束
结束

a = ConcreteThing.new
a.method_two#->引发错误。

但是,这似乎很少必要。


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?

解决方案

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天全站免登陆