我想知道如何动态创建attr_accessor。是否可以做类似的事情:
attr_accessor "@#{key}"
在initialize方法中?
module Mymodule
def initialize(parameters = {})
parameters.each do |key, value|
instance_variable_set("@#{key}", value) unless value.nil?
end
end
end
class Myclass
include Mymodule
end
clazz = Myclass.new attr1: "Arg1", attr2: "Arg2", attr3: "Arg3"
# => #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3">
clazz.attr1
# !> NoMethodError: undefined method `attr1' for #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3">
clazz.attr1="ATTR1"
# !> NoMethodError: undefined method `attr1=' for #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3">
答案 0 :(得分:6)
您可以通过在该实例的单例类上调用attr_accessor
来定义每个实例访问者。
class Structy
def initialize(parameters = {})
parameters.each do |key, value|
singleton_class.send :attr_accessor, key
instance_variable_set "@#{key}", value
end
end
end