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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With