ruby中的多继承类型继承 [英] Multiple-Inheritance type class inheritance in ruby

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

问题描述

我有一个 Base 超类和一堆派生类,比如 Base :: Number 基础::颜色。我希望能够使用这些子类,就好像我继承了 Fixnum ,如果是 Number

I got a Base superclass and a bunch of derived classes, like Base::Number, Base::Color. I'd like to be able to use those child classes as if I they inherited from say Fixnum in the case of Number.

最好的方法是什么,同时让他们对 is_a做出适当的回应?基数

What's the best way to do this, while still having them respond appropriately to is_a? Base ?

所以,我应该可以做到

Number.new(5) + Number.new(6) # => 11
Number.new.is_a? Base         # => true

我想我可以混入Base,并覆盖is_a?,kind_of?和instance_of?方法,但希望有一种更清洁的方式。

I'm thinking I could mix-in Base, and overwrite the is_a?, kind_of? and instance_of? methods, but hopefully there's a cleaner way.

推荐答案

使用Ruby实际上非常简单:

This is actually quite simple using Ruby:

module Slugish
  attr_accessor :slug
  def loud_slug
    "#{slug}!"
  end
end

class Stringy < String
  include Slugish
end

class Hashy < Hash
  include Slugish
end

hello = Stringy.new("Hello")
world = Stringy.new("World")

hello.slug = "So slow"
world.slug = "Worldly"

hello.loud_slug      #=> "So slow!"
world.loud_slug      #=> "Worldly!"

hello.is_a?(Slugish) #=> true
world.is_a?(Slugish) #=> true

"#{hello} #{world}"  #=> "Hello World"

stuff = Hashy.new
stuff[:hello] = :world
stuff.slug = "My stuff"
stuff.loud_stug      #=> "My stuff!"
stuff.is_a?(Slugish) #=> true

这篇关于ruby中的多继承类型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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