声明实例变量迭代哈希!
我想做以下事情:
我想声明迭代字典的类的实例变量。
假设我有这个哈希
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
我知道这不起作用!我只是放这段代码来看看你是否能更清楚地理解我想要的东西。
谢谢!
i want to do the following:
I want to declare the instance variables of a class iterating over a dictionary.
Let's assume that i have this hash
hash = {"key1" => "value1","key2" => "value2","key3" => "value3"}
and i want to have each key as instance variable of a class. I want to know if i could declare the variables iterating over that hash. Something like this:
class MyClass
def initialize()
hash = {"key1" => "value1","key2" => "value2","key3" => "value3"}
hash.each do |k,v|
@k = v
end
end
end
I know this doesn't work! I only put this piece of code to see if you could understand what i want more clearly.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
http://facets.rubyforge.org/apidoc/api/more/类/OpenStrutable.html
http://facets.rubyforge.org/apidoc/api/more/classes/OpenStructable.html
特征类是一个只属于单个对象的特殊类,因此定义的方法将具有该对象的实例方法,但不属于该对象普通类的其他实例。
The eigenclass is a special class belonging just to a single object, so methods defined there will be instance methods of that object but not belong to other instances of the object's normal class.
查克的回答比我前两次的尝试要好。 eigenclass 并不像我想象的那样
self.class
;我花了比我写的更好的测试来认识到这一点。使用我的旧代码,我按以下方式进行测试,发现该类确实被操纵,而不是实例:
输出是:
这显然反驳了我的假设。抱歉,查克,你一直都是对的。
旧答案:
attr_accessor
仅在类定义中评估时才起作用,而不是在实例的初始化中评估。因此,直接执行您想要的操作的唯一方法是将instance_eval
与字符串一起使用:要测试此尝试:
Chuck's answer is better than my last two attempts. The eigenclass is not
self.class
like I had thought; it took a better test than I had written to realize this.Using my old code, I tested in the following manner and found that the class was indeed manipulated and not the instance:
The output was:
This clearly disproves my presupposition. My apologies Chuck, you were right all along.
Older answer:
attr_accessor
only works when evaluated in a class definition, not the initialization of an instance. Therefore, the only method to directly do what you want is to useinstance_eval
with a string:To test this try: