0

I simply want to convert a string like this:

str = "tree dog orange music apple"

Into an array like this:

arr = ["tree", "dog", "orange", "music", "apple"]

I tried going down a path like this before realizing it's a dead end:

str = "tree dog orange music apple"
# => "tree dog orange music apple"
str.gsub!(" ", ", ")
# => "tree, dog, orange, music, apple"
arr = str.to_a
# ["tree, dog, orange, music, apple"]

Any help would be much appreciated. Thanks!

3 Answers 3

3

The String split method will do nicely:

str.split(' ')

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

Comments

1

array = str.split

Comments

0

Also of potential interest:

arr = %w{tree dog orange music apple} 

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.