I have an item ActiveRecords and I am trying to set a default value (“Test item”) for each of them using a block.
In this expression:
list = {"type1", "type2", "type3", "type4", "..."}
list.each { |name| @item.attributes["#{name}"] = "Test item"] }
values aren’t set.
I must use @item.attributes["#{name}"] for interpolation because I can’t do this for every item:
@item.tipe1 = "Test item"
So, what happens in the first statement? Why? If what I would like to do is not possible in that way, how I can do the same?
The assignment
@items.attributes["#{name}"] = "Test item"]does not work, because theattributesmethod returns a new Hash object each time you call it. So you are not changing the value of the@items‘ object as you thought. Instead you are changing the value of the new Hash that has been returned. And this Hash is lost after each iteration (and of course when theeachblock has finished).A possible solution would be to create a new Hash with the keys of the
@items‘ attributes and assign this via theattributes=method.