Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

Module.new

() ?{ (::Module mod) [self: ::Module] -> void } -> ::Module
Module.new → new_module
Module.new {|module| ... } → new_module

Returns a new anonymous module.

The module may be assigned to a name, which should be a constant name in capitalized camel case (e.g., MyModule, not MY_MODULE).

With no block given, returns the new module.

Example
MyModule = Module.new
MyModule.class # => Module
MyModule.name  # => "MyModule"

With a block given, calls the block with the new (not yet named) module:

Example
MyModule = Module.new {|m| p [m.class, m.name] }
# => MyModule
MyModule.class # => Module
MyModule.name  # => "MyModule"

Output (from the block):

Example
[Module, nil]

The block may define methods and constants for the module:

Example
MyModule = Module.new do |m|
  MY_CONSTANT = "#{MyModule} constant value"
  def self.method1 = "#{MyModule} first method (singleton)"
  def method2 =      "#{MyModule} Second method (instance)"
end
MyModule.method1 # => "MyModule first method (singleton)"
class Foo
  include MyModule
  def speak
    MY_CONSTANT
  end
end
foo = Foo.new
foo.method2      # => "MyModule Second method (instance)"
foo.speak
# => "MyModule constant value"