Back

Modifying a subset of an array

I recently needed to increment a subset of an array of integers. Essentially I had an array that looked something like this:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

And I needed to change it to this:

[1, 1, 1, 1, 1, 2, 2, 2, 2, 2]

Should be easy enough, right? Let’s fire up irb and do a little experiment.

> a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
 => [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 
> a[5..9].collect! { |el| el += 1 }
 => [2, 2, 2, 2, 2] 
> a
 => [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 

The array is left unchanged. Why? Because a[5..9] not the same object as a, so the object that collect! is modifying is not the original array. The way I ended up writing this code was:

a[5..9] = a[5..9].collect { |el| el += 1 }

Which accomplishes the goal with only a little more code.

Leave a Reply

Your email address will not be published. Required fields are marked *