Skip to content

Instantly share code, notes, and snippets.

@eregon
Created August 6, 2011 17:45
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 eregon/1129567 to your computer and use it in GitHub Desktop.
Save eregon/1129567 to your computer and use it in GitHub Desktop.
original_object_constants = Object.constants
O = "on Object"
class StaticClass
A = "on StaticClass"
end
DynamicClass = Class.new do # or Module.new
B = "on Object"
self::C = "on this class"
end
StaticClass::D = "on StaticClass"
StaticClass.class_eval { E = "on Object" } # or class_exec
StaticClass.class_eval 'F = "on StaticClass"'
puts "Constants of StaticClass: #{StaticClass.constants}"
puts "Constants of DynamicClass: #{DynamicClass.constants}"
puts "Constants of Object: #{Object.constants - original_object_constants}"
# constant resolution
class Parent
def const
# CONST # uninitialized constant Parent::CONST (NameError)
self.class::CONST
end
end
class Child < Parent
CONST = :const
end
Child.new.const
# class/module definition
C1 = Class.new do
module M # toplevel
end
end
p M
C2 = Class.new do
module self::M # in this class
end
end
p C2::M # => #<Class:0x00000100ad6550>::M
Constants of StaticClass: [:A, :D, :F]
Constants of DynamicClass: [:C]
Constants of Object: [:O, :StaticClass, :B, :DynamicClass, :E]
M
#<Class:0x0000010108b658>::M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment