在Ruby中,有没有办法动态地将实例变量添加到类中?例如:
class MyClass
def initialize
create_attribute("name")
end
def create_attribute(name)
attr_accessor name.to_sym
end
end
o = MyClass.new
o.name = "Bob"
o.name
一种方法(还有其他方法)是使用instance_variable_set
and instance_variable_get
如此:
class Test
def create_method( name, &block )
self.class.send( :define_method, name, &block )
end
def create_attr( name )
create_method( "#{name}=".to_sym ) { |val|
instance_variable_set( "@" + name, val)
}
create_method( name.to_sym ) {
instance_variable_get( "@" + name )
}
end
end
t = Test.new
t.create_attr( "bob" )
t.bob = "hello"
puts t.bob
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)