3

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.

2
  • Where are you specifying the indexes? Commented Nov 25, 2017 at 16:10
  • I haven't in this method because I'm not sure how to. The method should specify the index somewhere. Commented Nov 25, 2017 at 16:13

2 Answers 2

3

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]
Sign up to request clarification or add additional context in comments.

Comments

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]

1 Comment

I need to update each array element #=> [0, 1, 1, 0, 0] rather than just combine them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.