Question. In which namespace `B` is defined?
```ruby
A = Class.new do
B = 1
end
A::B # => ???
B # => ???
```
More on the topic https://fili.pp.ru/leaky-constants.html
@phil_pirozhkov very interesting. Away from IRB, I’m trying to figure out if this is a lexical scope thing, or a block/closure thing, or both… my hunch is it’s mostly the former though.
@james Couldn't find a better answer than this https://github.com/rspec/rspec-core/issues/2181#issuecomment-190535022
@phil_pirozhkov I'm back at the computer, and I'm pretty sure it's lexical scope at play.
When we write `Class.new do ... end`, the lexical scope of the block is the same level as `Class.new`, and that's where the constant is defined.
We can demonstrate this by changing scope by moving into a new class or module:
class Foo
Bar = Class.new do
A = 123
end
end
Foo::Bar::A # => Uninitialized constant A ..
Foo::A # => 123
Always fun figuring this stuff out!
@james You're right, the wording it's defined in top-level namespace is incorrect, should be the same scope as the block containing it. 👍