Ruby - Class Nested Classes

Introduction

Ruby can define classes within other classes.

These are called nested classes.

Here's an example:

class Drawing 
  class Line 
  end 

  class Circle 
  end 
end 

Nested classes are defined in the same way as usual. However, they're used differently.

From within Drawing, you can access the Line and Circle classes directly.

From outside the Drawing class, you can only access Line and Circle as Drawing::Line and Drawing::Circle.

For example:

Demo

class Drawing 
  def Drawing.give_me_a_circle 
    Circle.new #  w ww.  j a v a 2  s.co m
  end 

  class Line 
  end 

  class Circle 
    def what_am_i 
      "This is a circle" 
             end 
           end 
         end 

a = Drawing.give_me_a_circle 
puts a.what_am_i 
a = Drawing::Circle.new 
puts a.what_am_i 
a = Circle.new 
puts a.what_am_i

Result

a = Drawing.give_me_a_circle calls the give_me_a_circle class method, which returns a new instance of Drawing::Circle.

Next, a = Drawing::Circle.new gets a new instance of Drawing::Circle directly, which also works.

Related Topics