0

I have 2 arrays in ruby

firstarray = ["1212","3434"]
secondarray = ["9999","6666","7777"]

I want to merge these 2 arrays into thirdarray and thirdarray should have following structure-

thirdarray = ["1212","3434","9999","6666","7777"]

I was planning to use this:

thirdarray = [firstarray, secondarray.join(", ")]

but this gives me below which does not have " " around individual values 9999, 6666, 7777.

["1212", "3434", "9999 , 6666 , 7777"]

How can I do that?

3 Answers 3

4

Just use the + operator on those two arrays.

firstarray = ["1212","3434"]
secondarray = ["9999","6666","7777"]

thirdarray = firstarray + secondarray

=> ["1212", "3434", "9999", "6666", "7777"]
Sign up to request clarification or add additional context in comments.

3 Comments

what if I have to populate an array with this secondarray and 2 strings?eg - thirdarray = String2 + String3+ secondarray
You could use the splat operator: thirdarray = [*secondarray, "String2", "String3"]
@user6378152 If this doesn't answer your question then please edit it and clarify.
0

You can also use concat operator.

Below edits your 'firstarray' by appending your 'secondarray' elements to the end of 'firstarray'. concat is more performant than '+'

firstarray.concat(secondarray)

Comments

0

another way:

> thirdarray = [*firstarray, *secondarray]
#=> ["1212", "3434", "9999", "6666", "7777"]

if you want to add extra elements:

> thirdarray = [*firstarray, *secondarray, "additional-1" ]
#=> ["1212", "3434", "9999", "6666", "7777", "additional-1"] 

Comments

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.