Chad Johnson
Chad Johnson

Reputation: 21895

module module class vs. module module::class in Ruby

What is the difference between

module MyModule
  module MySubModule
    class MySubModuleClass
      ...
    end
  end
end

and

module MyModule
  class MySubModule::MySubModuleClass
    ...
  end
end

in Ruby?

Upvotes: 1

Views: 169

Answers (2)

Tilo
Tilo

Reputation: 33732

the second case will not work unless "MySubModule" is already defined elsewhere...

the second case is not a proper definition of "MySubModule" and will cause an error if you didn't define that MySubModule elsewhere

NameError: uninitialized constant MyModule::MySubModule
    from (irb):2:in `<module:MyModule>'

Upvotes: 1

Guilherme Bernal
Guilherme Bernal

Reputation: 8293

On the second example you are defining a class, in the first is a module, and you can't use the syntax MySubModule::MySubModuleClass if MySubModule does not exist. So you have to have it defined before.

Upvotes: 1

Related Questions