ruby - Insert items into an array while iterating -


how modify (add/remove elements) array while iterating on , have iterator aware of it?

for example think code:

a = "1234567890".split("") a.each_with_index{|d, i|  if d.eql?('5')   a.delete_at(i)   a.insert(i, ['a', 'b', 'c'] )  end print d } 

would produce: 1234abc67890 instead produces 1234567890

is there workaround or different method make work?

(i know example pretty simple example doing complicated text processing need insert text when hit key word. bunch of functions before , after expansion doing insert outside of each loop [aka map!] complicate code)

actually, code works, need replace print d print a[i] since you're printing variable d not actual array element @ index i

rather deleting , inserting, why not change element on index?

    = "1234567890".split("")     a.each_with_index{|d, i|      if d.eql?('5')       a[i] = ['a','b','c']      end     print a[i] #a[i] rather d, since d contains old value     } 

or

 ... if d.eql?('5')    a[i] = ['a','b','c']    d = a[i] end print d 

deleting/inserting on array during iterations discourage since may cause headaches haha... resort other methods if possible :)

note: i've used current logic in code based on understanding, , given desired output

the array become [1,2,3,4,['a','b','c'],6,7,8,9,0] , not [1,2,3,4,'a','b','c',6,7,8,9,0]. if want other, leave comment :)

if want change value in string, can use .tr or .gsub job


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -