"value1","key2" => "value2","key3" => "value3-6ren">
gpt4 book ai didi

ruby - 声明实例变量遍历哈希!

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

我想做以下事情:

我想声明一个遍历字典的类的实例变量。

假设我有这个散列

hash = {"key1" => "value1","key2" => "value2","key3" => "value3"}

并且我想将每个键都作为类的实例变量。我想知道我是否可以声明迭代该散列的变量。像这样:

class MyClass
def initialize()
hash = {"key1" => "value1","key2" => "value2","key3" => "value3"}
hash.each do |k,v|
@k = v
end
end
end

我知道这行不通!我只是放了这段代码,看看你是否能更清楚地理解我想要什么。

谢谢!

最佳答案

class MyClass
def initialize()
hash = {"key1" => "value1","key2" => "value2","key3" => "value3"}
hash.each do |k,v|
instance_variable_set("@#{k}",v)
# if you want accessors:
eigenclass = class<<self; self; end
eigenclass.class_eval do
attr_accessor k
end
end
end
end

特征类是一个只属于单个对象的特殊类,因此定义在那里的方法将是该对象的实例方法,但不属于该对象的普通类的其他实例。

关于ruby - 声明实例变量遍历哈希!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1615190/

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