Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add arrays to an array without creating a 2D array

Tags:

arrays

ruby

I have an array word_array, and I'd like to add all the words of sentences to it. For example:

word_array = []
sentence_1 = "my first sentence"
sentence_2 = "my second sentence"

and then have:

word_array = ["my", "first", "sentence", "my", "second", "sentence"]

If I use split():

word_array << sentence_1.split
word_array << sentence_2.split 

I get:

word_array = [["my", "first", "sentence"], ["my", "second", "sentence"]]

How can I avoid having a 2D array here?

like image 835
Graham Slick Avatar asked Dec 11 '22 19:12

Graham Slick


1 Answers

Use concat.

word_array.concat(sentence_1.split)
word_array.concat(sentence_2.split)

It is more efficient than using +, which makes a new array.

like image 188
sawa Avatar answered Jan 01 '23 07:01

sawa