Ruby - Class Partial Classes

Introduction

You can define a single class in separate parts of your program.

When a class descends from a specific superclass, each subsequent partial class definition may repeat the superclass in its definition using the < operator.

The following code creates one class, A, and another that descends from it, B:

Demo

class A 
    def a # from   www .ja  v a  2 s  .c om
       puts( "a" ) 
    end 
end 

class B < A 
    def ba1 
       puts( "ba1" ) 
    end 
end 

class A 
    def b 
       puts( "b" ) 
    end 
end 


class B < A 
   def ba2 
      puts( "ba2" ) 
   end 
end 


ob = B.new 
ob.a 
ob.b 
ob.ba1 
ob.ba2

Result

Here, if I create a B object, all the methods of both A and B are available to it:

Related Topics