Created
September 1, 2009 09:32
-
-
Save s-andringa/179008 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Object | |
def metaclass | |
class << self; return self; end | |
end | |
end | |
class Foo | |
# 1. def within class definition | |
def self.set_a | |
@@a = true | |
end | |
end | |
# 2. def outside class definition | |
def Foo.set_b | |
@@b = true | |
end | |
# 3. class_eval | |
Foo.class_eval do | |
def self.set_c | |
@@c = true | |
end | |
end | |
# 4. instance_eval | |
Foo.instance_eval do | |
def self.set_d | |
@@d = true | |
end | |
end | |
# 5. define_method on metaclass | |
Foo.metaclass.send :define_method, :set_e do | |
@@e = true | |
end | |
# 6. Include module into metaclass | |
module SetF | |
def set_f | |
@@f = true | |
end | |
end | |
Foo.metaclass.send :include, SetF | |
# 7. Extend with module | |
module SetG | |
def set_g | |
@@g = true | |
end | |
end | |
Foo.extend SetG | |
# Output: | |
print "Variable\tOn class?\tOn metaclass?\n\n" | |
("a".."g").each do |var| | |
Foo.send("set_#{var}") | |
print "@@" + var + "\t\t" | |
print (Foo.class_variables.include?("@@#{var}") ? Foo.send(:class_variable_get, "@@#{var}").to_s : "-") + "\t\t" | |
print (Foo.metaclass.class_variables.include?("@@#{var}") ? Foo.metaclass.send(:class_variable_get, "@@#{var}").to_s : "-") + "\n" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment