Created
July 24, 2013 17:23
-
-
Save dalang/6072610 to your computer and use it in GitHub Desktop.
test dynamically add instance_variables or class_variables to class.
This file contains 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 Mine | |
@xxx = 1 | |
attr_accessor :some_var | |
def intialize | |
@some_var = true | |
end | |
class << self | |
def my_number num | |
attr_accessor "my_#{num}" | |
p self | |
self.instance_variable_set("@my_#{num}", num) | |
# self.send("my_#{num}=", num) | |
p self.methods.select {|x| x.start_with? "class"} | |
class_variable_set("@@my_#{num}", num) | |
# class_eval("@@class_#{num} = :m%s" % num.to_s) | |
end | |
end | |
end | |
dude = Mine.new | |
Mine.my_number 1 | |
puts dude.class.instance_variables | |
puts dude.class.class_variables | |
puts "---------" | |
class Widget | |
# class instance variable pattern | |
class << self; attr_accessor :color; end | |
attr_accessor :size, :type | |
def initialize() | |
@yyy = 10 | |
end | |
def show_color() | |
"This widget is #{self.class.color}" | |
end | |
end | |
# Widget.color = 100 | |
puts Widget.instance_variables | |
puts "------------" | |
wdg = Widget.new | |
wdg.size = 10 | |
puts wdg.instance_variables |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment