#### Topic: Array question

I have an array like
[1,2,3,4,5,6,7,8,9,10]

I want to add 3 to elements from index 4 to 7:

[1,2,3,4,8,9,10,11,9,10]

How can I do that in the simplest way ?

thanks

#### Re: Array question

`a = [1,2,3,4,5,6,7,8,9,10]a[4, 4] = [8,9,10,11]a    #=> [1, 2, 3, 4, 8, 9, 10, 11, 9, 10]`

Array Element Assignment Documentation:
http://ruby-doc.org/core/classes/Array.html#M002184

Vincent Woo Ruby on Rails Blog

#### Re: Array question

thanks vwoo for your example, but all elements are dynamically constructed.

here is a working example:
a.each_index {|i| a[i]=a[i]+1 if i>=4 and i<=7}

is there a simpler way than that (without traverse the whole array?

#### Re: Array question

Here is a couple of ways to iterate only through a subset of the array:

`original = (1..10).to_aa = original.clonea.each_index {|i| a[i]=a[i]+1 if i>=4 and i<=7}#=> a is now [1, 2, 3, 4, 6, 7, 8, 9, 9, 10]b = original.clone4.upto(7) {|i| b[i] += 1}#=> b is now [1, 2, 3, 4, 6, 7, 8, 9, 9, 10]c = original.clone(4..7).each {|i| c[i] += 1}#=> c is now [1, 2, 3, 4, 6, 7, 8, 9, 9, 10]`

Vincent Woo Ruby on Rails Blog