From: Robert Klemme Date: 2011-09-05T16:12:51+09:00 Subject: Re: loops problem On Sun, Sep 4, 2011 at 5:21 PM, Josh Cheek wrote: > On Sun, Sep 4, 2011 at 9:45 AM, jack jones wrote: > >> I've read about the method which inserts some element in a certain place >> .. >> what I wanted to do is to shift all the elements to the back .. not >> inserting which will require rather complicated operation like deleting >> the element after shifting it .... I really don't understand the line >> you wrote, thank you :) > Insert nil. There are lots of options for docs. > rdoc.info: http://rdoc.info/stdlib/core/1.9.2/Array#insert-instance_method > ruby-doc.org: http://ruby-doc.org/core/classes/Array.html#M000230 > > And you can't have an array with a "gap" in it. ie what is returned if you > access that index after you've shifted the elements? The obvious answer is > nil, so just insert nil: > > array = (0..10).to_a > counter = 5 > array.insert counter, nil > array # => [0, 1, 2, 3, 4, nil, 5, 6, 7, 8, 9, 10] And if the length should stay the same an additional array.pop will remove the last element. Btw, for inserting multiple elements one can do: irb(main):004:0> a=10.times.to_a => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] irb(main):005:0> a[5,0] = Array.new 3 => [nil, nil, nil] irb(main):006:0> a.pop 3 => [7, 8, 9] irb(main):007:0> a => [0, 1, 2, 3, 4, nil, nil, nil, 5, 6] irb(main):008:0> a.length => 10 Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/