ruby中的多继承类型继承

clo*_*ead 6 ruby oop inheritance

我有一个Base超类和一堆派生类,比如Base::Number,Base::Color.我希望能够使用这些子类,如果我从他们继承说Fixnum在的情况下Number.

什么是最好的方法,同时仍然让他们适当回应is_a? Base

所以,我应该能做到

Number.new(5) + Number.new(6) # => 11
Number.new.is_a? Base         # => true
Run Code Online (Sandbox Code Playgroud)

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

Yeh*_*atz 13

使用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
Run Code Online (Sandbox Code Playgroud)