gpt4 book ai didi

Ruby:如何即时创建 attr_accessor

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:30 27 4
gpt4 key购买 nike

我想知道如何即时创建 attr_accessor。是否可以做类似的事情:

attr_accessor "@#{key}" 

在初始化方法中?

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">

最佳答案

您可以通过在该实例的单例类上调用 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

关于Ruby:如何即时创建 attr_accessor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45796806/

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