在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
Run Code Online (Sandbox Code Playgroud)
Ree*_*ore 26
一种方式(还有其他方式)是使用instance_variable_set
和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
Run Code Online (Sandbox Code Playgroud)