我知道在Ruby中執行for
循環的慣用方法是使用像.each
這樣的枚舉器,但我遇到了一個問題:我想迭代Array的子集並修改這些元素。調用.map!
與子集如ary[0..2]
或.slice(0..2)
似乎並沒有這樣做;大概是因爲切片操作員正在創建一個新的數組?如何迭代修改Ruby中的數組子集?
期望的行爲與for
而不是迭代器:
iter_ind = [2,3,4]
my_ary = [1,3,5,7,9,11]
for j in iter_ind
my_ary[j] = my_ary[j] + 1
# some other stuff like an exchange operation maybe
end
=> [1, 3, 6, 8, 10, 11]
東西不起作用:
irb(main):032:0> ar[2..4].map! {|el| el = el+1}
=> [6, 8, 10]
irb(main):033:0> ar
=> [1, 3, 5, 7, 9, 11]
irb(main):034:0> ar.slice(2..4).map! {|el| el = el+1}
=> [6, 8, 10]
irb(main):035:0> ar
=> [1, 3, 5, 7, 9, 11]
irb(main):036:0> ar[2..4].collect! {|el| el = el+1}
=> [6, 8, 10]
irb(main):037:0> ar
=> [1, 3, 5, 7, 9, 11]
感謝您的編輯,我必須意外地點擊了建議的標籤。 –