Question. In which namespace `B` is defined?

A = do
B = 1
A::B # => ???
B # => ???

More on the topic

@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 ` do ... end`, the lexical scope of the block is the same level as ``, 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 = do
A = 123

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

A Mastodon instance for Rubyists & friends