开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜