Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Module Constant oddity
module Mod
A = :a
const_set('B', :b)
end
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)
end
Mod::A #=> :a
Mod::B #=> :b
Mod::C #=> uninitialized constant Mod::C
Mod::D #=> :d
::C #=> :c
Owner

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
end

Mod::C #=> :c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment