Ruby: Defining attributes by looping an array?
I'm trying to define attributes from an array like so:
["a", "b", "c"].each do |field|
@recipe.field = "anything"
end
I want to end up with something like this:
@store.a = "anyth开发者_运维问答ing"
@store.b = "anything"
@store.c = "anything"
Do you know what I should do with the @store.field above? I tried @store.send(field), but that is not working for me and I have no idea what keywords to search to find a solution to the above. Any help is greatly appreciated.
The setter method for attribute a
is known as a=
, so you can use send
with an argument "a="
to call the setter method:
["a", "b", "c"].each do |field|
@recipe.send(field + "=", "anything")
end
If you want to dynamically add attributes to class, then you should use attr_accessor
mthod (or check what it does
class Recipe
attr_accessor *["a", "b", "c"]
end
["a", "b", "c"].each do |field|
@recipe.send("#{field}=", "anything")
end
Edit:
As you see in example, if you want to assign something to field defined by def attr=
method, then you need to call send
with "attr=", value
params.
精彩评论