如何根据元素在数组中的索引位置分配属性?

How do I assign an attribute based on where an element's index within an array?

我正在使用 Ruby 2.4。假设我有一个对象数组,每个对象的类型都是 "MyData"。每个 MyData 对象都有一个属性 "attr1"。给定我的数组

[myobj1, myobj2, myobj3, ...]

如何根据属性 "attr1" 在数组中的位置为其赋值?例如,数组中的第一个对象将 "attr1" 设置为“1”,第二个对象将其设置为“2”,依此类推。

试试这个。 a 是你的数组

a.each_with_index { |item, index| item.attr1 = index + 1 }