tags:

views:

39

answers:

2

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 = "anything"
@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.

+1  A: 

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.

MBO
Thank you MBO! You and Brian are awesome. Thank you!
andy
+4  A: 

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
Brian Campbell
Thank you so much, Brian =) I really appreciate it!
andy