Follow

Question. In which namespace `B` is defined?

```ruby
A = Class.new do
B = 1
end
A::B # => ???
B # => ???
```

More on the topic fili.pp.ru/leaky-constants.htm

@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.

@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. 👍

@phil_pirozhkov congrats on the Ruby Weekly mention! It's a shame that the headline contained the slightly misleading explanation though, but still. Nice! :)

@james Thanks!

Seems they've added it before I've made a correction to the article basing on your lexical scope remark.

Sign in to participate in the conversation
Ruby.social

A Mastodon instance for Rubyists & friends