Why would we put a module inside a class in Ruby?

后端 未结 4 677
遇见更好的自我
遇见更好的自我 2021-01-30 04:01

In Ruby, I see that it can be useful to put classes inside modules for the sake of namespacing. I also see that it\'s possible to put modules inside classes. But I don\'t see wh

4条回答
  •  长情又很酷
    2021-01-30 04:42

    I guess it’s really just about using a class as a namespace, which is sometimes just more convenient that putting everything in a module. I’ve never seen that in practice, but it’s perfectly valid Ruby code either way.

    The only real-life scenario I can think of is using EventMachine in a class:

    class Api
      def initialize
        EM.start_server "0.0.0.0", 8080, Server
      end
    
      module Server
        def receive_data (data)
          # do stuff
        end
      end
    end
    

提交回复
热议问题