Reputation:
I'm using Ruby 2.4. Let's say I have an array of objects, each of type "MyData". Each MyData object has an attribute "attr1". Given my array
[myobj1, myobj2, myobj3, ...]
how do I assign a value to the attribute "attr1" based on its position within the array? FOr example, the first object in the array would hvae "attr1" set to "1", the second would have it set to "2," and so on.
Upvotes: 1
Views: 44
Reputation: 30056
Try this one. a
is your array
a.each_with_index { |item, index| item.attr1 = index + 1 }
Upvotes: 3