2

I have an array like this

array = ["My Name", "1905", "more than three words"]

What I would like to do is split each item of the array by its space and then create 1 array with each word, so

["My", "Name", "1905", "more", "than", "three", "words"]

What I have tried so far is

words = []
array.each do { |a| words << a.to_s.split(" ") }

This returns

[["My", "Name"], ["1905"], ["more", "than", "three", "words"]]

But I have multiple arrays within an array. How would I go about achieving

["My", "Name", "1905", "more", "than", "three", "words"]

I'm missing something obvious aren't I?

1
  • simply flatten the array, see answer below. Commented Jul 9, 2015 at 14:02

4 Answers 4

4

You need to flatten it, or do flatten while mapping.

array.flat_map{|e| e.split(" ")}

You can also do this:

array.inject([]){|a, s| a + s.split(" ")}
Sign up to request clarification or add additional context in comments.

Comments

3

Try this:

array.join(' ').split(' ')

Example:

["My Name", "1905", "more than three words"].join(' ').split(' ') # => ["My", "Name", "1905", "more", "than", "three", "words"]

Comments

3

This should give you the output that you want.

array.join(" ").split

Alternative using scan:

array.join(" ").scan(/\S+/)

Comments

0
array.collect { |a| a.split(" ") }.flatten 
#=> ["My", "Name", "1905", "more", "than", "three", "words"]

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.