使用 attr_accessor 动态创建类属性 [英] Dynamically Create Class Attributes with attr_accessor
本文介绍了使用 attr_accessor 动态创建类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Ruby 中,有没有办法动态地将实例变量添加到类中?例如:
In Ruby, is there a way to dynamically add a instance variable to a class? For Example:
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
和 instance_variable_get
如下:
One way (there are others) is to use instance_variable_set
and instance_variable_get
as so:
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
这篇关于使用 attr_accessor 动态创建类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文