@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:
Bar = Class.new 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! :)
Seems they've added it before I've made a correction to the article basing on your lexical scope remark.
A Mastodon instance for Rubyists & friends