From: "Kroeger Simon (ext)" Date: 2005-09-06T17:29:12+09:00 Subject: Re: [Q] how to do insertion and smooth traversal simultaneously on array > -----Original Message----- > From: Robert Klemme [mailto:bob.news@gmx.net] > Sent: Tuesday, September 06, 2005 10:26 AM > To: ruby-talk ML > Subject: Re: [Q] how to do insertion and smooth traversal > simultaneously on array > > Kroeger Simon (ext) wrote: > > as Robert said: > > ----------------------------------------------------------------- > > a = [ 0, 1, 2, 3, 4, 5 ] > > actions = [] > > a.each_with_index do |x, i| > > puts "[#{i}] : #{x}" > > if i % 2 == 0 # even index ? > > actions << [a, :insert, [i, ':-)']] > > end > > end > > # do it! > > actions.reverse.each{|action| action[0].send(action[1], *action[2])} > > puts a.size > > ------------------------------------------------------------------ > > You can slightly simplify this as > > a = [ 0, 1, 2, 3, 4, 5 ] > actions = [] > a.each_with_index do |x, i| > puts "[#{i}] : #{x}" > if i % 2 == 0 # even index ? > actions << [a, [:insert, i, ':-)']] > end > end > # do it! > actions.reverse.each{|obj, args| obj.send(*args)} > puts a.size, "", a > > Although I like the idea to use #send in this case a simpler solution > would be sufficient: > > a = [ 0, 1, 2, 3, 4, 5 ] > actions = [] > a.each_with_index do |x, i| > puts "[#{i}] : #{x}" > if i % 2 == 0 # even index ? > actions << [i, ':-)'] > end > end > # do it! > actions.reverse.each{|idx, val| a.insert(idx, val)} > puts a.size, "", a > > Kind regards > > robert :) in _this_ case somrthing like this would sufficient: a = [ 0, 1, 2, 3, 4, 5 ] (a.size / 2).times {|i| a.insert(i*3, ':-)')} cheers Simon