Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge array at specific index in Ruby

Tags:

arrays

ruby

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.

like image 503
safikabis Avatar asked Nov 20 '25 05:11

safikabis


1 Answers

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]
like image 198
Simple Lime Avatar answered Nov 22 '25 20:11

Simple Lime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!