Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
Module Constant oddity
module Mod
A = :a
const_set('B', :b)
Mod.module_exec do
C = :c #This seems to just vanish entirely, but its actually being assigned elsewhere. See comments below.
const_set('D', :d)
Mod::A #=> :a
Mod::B #=> :b
Mod::C #=> uninitialized constant Mod::C
Mod::D #=> :d
Copy link

trptcolin commented Feb 8, 2014

::C #=> :c

Copy link

jah2488 commented Feb 12, 2014

Colin is right, it seems that, due to a 'quirk' in the way ruby parses and evaluates the assignments of constants. They are set to the global namespace when attempted to be assigned in a block such as module_exec. This can be worked around by explicitly declaring the namespace, but it might not always be useful.

Mod.module_exec do
  Mod::C = :c

Mod::C #=> :c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment