Can anonymous modules and class be nested in Ruby?

I can define an anonymous class in an anonymous module:

c = nil
m = Module.new do
  c = Class.new
end

m #=> #<Module:0x007fad3a055660>
c #=> #<Class:0x007fad3a0555e8>

Is the above equivalent:

m = Module.new
c = Class.new

In other words: does the concept of nesting really apply to anonymous modules?

+4
source share
1 answer

This does not mean to be anonymous. Assigning a dynamically created class to a constant makes it a name:

Foo = Class.new # => Foo
foo = Class.new # => #<Class:0x007fe5dd45d650>

However, he still does not nest further:

module Bar
  Baz = Module.new do
    p Module.nesting # => [Bar]
  end
end

Or even about being dynamic:

module Quz
  eval 'module Qux; p Module.nesting; end' # => [Quz::Qux, Quz]
end

This is about the gates of the area.


As for the constants, there are only two shutters - the keywords classand module.

The attachment is purely syntactic. This is why you get weird:

module Do
  X = 42
end

module Do
  module Re
    p Module.nesting # => [Do::Re, Do]
    p X              # => 42
  end
end

module Do::Mi
  p Module.nesting # => [Do::Mi]
  p X # => uninitialized constant
end

Do.module_eval   { p X } # => uninitialized constant
Do.instance_eval { p X } # => uninitialized constant

, Ruby class module, " node". end, . , node.

+2

Source: https://habr.com/ru/post/1662413/


All Articles