1

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.

1 Answer 1

3

Try this one. a is your array

a.each_with_index { |item, index| item.attr1 = index + 1 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.