2

This is below is an example of superclass/subclass construct :

C:\>irb --simple-prompt
>> class Parent
>> @@x = 10
>> end
=> 10
>> class Child < Parent
>> @@x = 12
>> end
=> 12
>> class Parent
>> puts "@@X = #{@@x}"
>> end
@@X = 12
=> nil

And the above is also understood.But I wanted to check if possible or not when two class are defined seprately as an standalone class anyway to define the super/sub relation between them?

I tried the below but it doesn't work. May be not the way I tried:

C:\>irb --simple-prompt
>> class Parent
>> @@X = 10
>> end
=> 10
>> class Child
>> @@x = 15
>> end
=> 15
>> class Child < Parent
>> def show
>> p "hi"
>> end
>> end
TypeError: superclass mismatch for class Child
        from (irb):7
        from C:/Ruby193/bin/irb:12:in `<main>'
>>
  • Dupe: http://stackoverflow.com/questions/3127069/how-to-dynamically-alter-inheritance-in-ruby . E.g. you cannot change the superclass after a class has been defined. – Dave S. May 30 '13 at 02:14

1 Answers1

0

You cannot change the superclass of a class after it's been declared in Ruby. However, if you want to include specific behavior on classes, you can extend them using modules.

module Parent
  def yell_at_kids
    puts "Stop hitting your brother!"
  end
end

class Child
  def have_children
    extend Parent
  end
end

Child.new.have_children.yell_at_kids

In this case, Parent is a module which may be included or extended into other objects (like an instance of our Child class here). You can't extend a class with another class, but you can extend a class with a module.

Chris Heald
  • 61,439
  • 10
  • 123
  • 137