Nested Classes in Ruby

October 10, 2007

You could create classes inside another classes in Ruby.  In Ruby, classes defined are stored as constants with same name as class. And as you know Ruby class definitions are executable code and it execute in the context of that class as the current object.   That means any classes (say B,C) defined  inside another class (A) would act like constants of that outer class ( as A::B, A::C).

 Lets look at some code

class A
  def test_method
    “I AM NOW IN CLASS A”
  end
  class B
    def test_method
      “I AM NOW IN CLASS B”
    end
  end
end
p A.new.test_method      –> “I AM NOW IN CLASS A”
p A::B.new.test_method   –> “I AM NOW IN CLASS B”

See how we accessed Class B as A::B

Leave a Reply