Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jah2488
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jah2488/8890318 to your computer and use it in GitHub Desktop.
Save jah2488/8890318 to your computer and use it in GitHub Desktop.
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
@trptcolin
Copy link

::C #=> :c

@jah2488
Copy link
Author

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