3

I am familiar with the concept of nesting classes and modules within another module and grouping them in a namespace. What is the idea / purpose behind

  1. Nesting classes within another class

    class A
      class B
        def method_B
          ...
        end
      end
    end
    
  2. Nesting modules within another class

    class A
      module c
        def method_c
          ...
        end
      end
    end
    

thanks, ash

2 Answers 2

3

Classes are also namespaces, so it's the same idea. Class is a subclass of Module, so if you get it in the context of modules, you also get it in the context of classes.

Sign up to request clarification or add additional context in comments.

Comments

1

It is all about grouping related concerns while exposing sensible semantics. As an example of number 1 an HTTP::Request (Request class embedded in a larger HTTP protocol class) is a quite different thing from an FTP::Request. With modules it enables the common ruby idiom of Behavior::InstanceMethods and Behavior::ClassMethods for handling mixins.

4 Comments

Those are examples of classes within modules, though, while the question is about classes in classes.
HTTP doesn't have to be a module. It could be a class depending on how the way you design the program.
So it is just a namespace and has no special behavior like, only enclosing class being able to create instances of the enclosed class?
@user290870: You don't nest classes and modules. You nest constants. Ruby doesn't have nested classes like Beta or Newspeak.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.