gpt4 book ai didi

ruby - 使用 attr_accessor 动态创建类属性

转载 作者:数据小太阳 更新时间:2023-10-29 06:47:47 24 4
gpt4 key购买 nike

在 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_setinstance_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

关于ruby - 使用 attr_accessor 动态创建类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4082665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com