5

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?

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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"]

1 Comment

I get an error "no implicit conversion of String into Array"
3

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.

Comments

1

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"]

3 Comments

In such case, inject or each_object would be more efficient. But your answer may be conceptually simpler. And is symbol-to-proc attracting you?
@sawa - Thanks. I was trying to avoid explicit call to flatten on split result.
I know. Using flatten is a bad idea in this case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.