Graham Slick
Graham Slick

Reputation: 6870

Add arrays to an array without creating a 2D array

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?

Upvotes: 5

Views: 98

Answers (4)

Wand Maker
Wand Maker

Reputation: 18762

It is likely that you may have more than one sentences, and you may be getting it in the form of array. Below solution will be apt in that case, as well as if you had only couple of sentences.

sentence_1 = "my first sentence"
sentence_2 = "my second sentence"

ary = [sentence_1, sentence_2]
words = ary.flat_map {|s| s.split}
#=> ["my", "first", "sentence", "my", "second", "sentence"]

Upvotes: 1

sawa
sawa

Reputation: 168101

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.

Upvotes: 6

Sefier Tang
Sefier Tang

Reputation: 790

Just use sentence_1.split + sentence_2.split

I think you may confuse + and << for array. + is to merge arrays, << takes the argument as the array's element.

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122383

One way is to use += to append the elements to the end of word_array every time:

word_array += sentence_1.split
# => ["my", "first", "sentence"]
word_array += sentence_2.split
# => ["my", "first", "sentence", "my", "second", "sentence"]

Upvotes: 4

Related Questions