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!
http://facets.rubyforge.org/apidoc/api/more/classes/OpenStructable.html
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:
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.