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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With