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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: