Ruby Multiple Inheritance Type Inheritance

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

What is the best way to do this while still having relevant answers to is_a? Base is_a? Base ?

So I have to be able to do

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

I think I can mix Base and overwrite is_a ?, kind_of? and instance_of? methods, but hopefully there is a cleaner way.

+6
inheritance oop ruby
source share
4 answers

This is actually pretty 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 
+13
source share

Why do you insist on using is_a? / Kind_of? when is response_to? is a much cleaner way to test things? You want objects to implement an interface / contract without being a subclass of any arbitrarily selected superclass. But maybe I missed some requirement here.

Change I understand your arguments, but this often leads to poor OO / dynamic design. Or you are doing something similar, which might be an acceptable idea in leaf classes, but within the framework you need to solve with inheritance:

 if a.is_a?(something) #do something elif a.is_a?(something_else) #do something else ... 

or something like this:

 if !a.is_a?(something) #raise condition/return null/etc. endif ... 

I think that rejecting an error code does not understand the language-based exception for message passing is an ideal design solution.

As an additional problem, using is_a? instead of response_to? limits your ability to use mock objects in unit testing. This can be a pretty big problem even for moderately complex code.

+3
source share

I think you are using inheritance incorrectly if you have completely unrelated classes, such as Number and Color, all from the same base class. Instead, I would use composition if they need access to the same routines (I don't know why they will do this).

+1
source share

Ruby, equivalent to multiple inheritance, is mixins. It seems to me that you want Base to be a module that mixes with several classes.

+1
source share

All Articles