如何在Ruby中实现一个抽象类? [英] How to implement an abstract class in ruby?

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

问题描述

我知道在ruby中没有抽象类的概念。但是,如果根本需要实施,该怎么做?我尝试过类似的事情……

I know there is no concept of abstract class in ruby. But if at all it needs to be implemented, how to go about it? I tried something like...

class A
  def self.new
    raise 'Doh! You are trying to write Java in Ruby!'
  end
end

class B < A
  ...
  ...
end

但是当我尝试实例化B时,它将在内部调用 A.new ,这将引发异常。

But when I try to instantiate B, it is internally going to call A.new which is going to raise the exception.

此外,模块不能被实例化,但是它们也不能被继承。将新方法设为私有也将不起作用。

Also, modules cannot be instantiated but they cannot be inherited too. making the new method private will also not work. Any pointers?

推荐答案

我不喜欢在Ruby中使用抽象类(几乎总有更好的方法)。如果您确实认为这是针对这种情况的最佳技术,则可以使用以下代码段更抽象地说明哪种方法:

I don't like using abstract classes in Ruby (there's almost always a better way). If you really think it's the best technique for the situation though, you can use the following snippet to be more declarative about which methods are abstract:

module Abstract
  def abstract_methods(*args)
    args.each do |name|
      class_eval(<<-END, __FILE__, __LINE__)
        def #{name}(*args)
          raise NotImplementedError.new("You must implement #{name}.")
        end
      END
      # important that this END is capitalized, since it marks the end of <<-END
    end
  end
end

require 'rubygems'
require 'rspec'

describe "abstract methods" do
  before(:each) do
    @klass = Class.new do
      extend Abstract

      abstract_methods :foo, :bar
    end
  end

  it "raises NoMethodError" do
    proc {
      @klass.new.foo
    }.should raise_error(NoMethodError)
  end

  it "can be overridden" do
    subclass = Class.new(@klass) do
      def foo
        :overridden
      end
    end

    subclass.new.foo.should == :overridden
  end
end

基本上,您只需调用抽象带有抽象方法的列表的ract_methods ,当它们被抽象类的实例调用时,将引发 NotImplementedError 异常。

Basically, you just call abstract_methods with the list of methods that are abstract, and when they get called by an instance of the abstract class, a NotImplementedError exception will be raised.

这篇关于如何在Ruby中实现一个抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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