2

I need a method which returns a merged array starting a specified index. I've looked here, here and here without cracking it.

I can see that this concatenates but I want to update the array not simply combine them:

@a1 = [0,0,0,0,0]

a2 = [1,1]

def update_array(new_array)
  @a1.push(*new_array)  
end

update_array(a2)

I'd like the output to be something like:

#[0,1,1,0,0] or [0,0,0,1,1]

Depending on the index specified.

Simple Lime
  • 10,790
  • 2
  • 17
  • 32
safikabis
  • 41
  • 6

2 Answers2

2

Arrays have a method which does that: insert

a1 = [0,0,0,0,0]
a2 = [1,1]

a1.insert(1, *a2) # => [0, 1, 1, 0, 0, 0, 0]
steenslag
  • 79,051
  • 16
  • 138
  • 171
2

You can use the normal element assignment, Array#[]= and pass in the start and length parameters:

Element Assignment — Sets the element at index, or replaces a subarray from the start index for length elements, or replaces a subarray specified by the range of indices.

(emphasis mine) So, for instance:

@a1 = [0,0,0,0,0]
a2 = [1,1]
@a1[1, a2.length] = a2
@a1 # => [0, 1, 1, 0, 0]
@a1 = [0,0,0,0,0]
@a1[@a1.length - a2.length, a2.length] = a2
@a1 # => [0, 0, 0, 1, 1]
Simple Lime
  • 10,790
  • 2
  • 17
  • 32