ruby - Will array.each work properly if the array is updated during each iteration? -


will method process each element of array if array being updated within code block of each loop?

for example:

arr.each |x|   if (x != 2)     arr.push(x+4)   end end 

will loop still iterate on every element within array, though being lengthened?

maybe


yes, if talking mri, , question is: "will iterator traverse new elements?".

if talking ruby language, "maybe". there no specification mri serves reference implementation.

but having said that, seems implementation-specific, partly because requiring specific behavior impose constraint on implementations no clear benefit, performance trade-offs.

it's quite imperative, it's perhaps not "the ruby way", leans more functional styles.

here how think ruby program should write sort of loop. expression return old array unless changes, in case creates new array in functional style there never doubt result be...

>> = [1, 2, 3] => [1, 2, 3] >> a.inject(a) { |m, e| e < 99 ? m + [99] : m } => [1, 2, 3, 99, 99, 99] 

a faster (if lots of new elements added) semi-functional expression be:

t = a.inject(a.dup) { |m, e| e < 99 ? m << 99 : m }  

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -