开发者

Converting Unformatted String Of Objects Into An Array

开发者 https://www.devze.com 2022-12-12 16:42 出处:网络
开发者_开发百科I simply want to convert a string like this: str = \"tree dog orange music apple\"

开发者_开发百科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!


The String split method will do nicely:

str.split(' ')


array = str.split


Also of potential interest:

arr = %w{tree dog orange music apple} 
0

精彩评论

暂无评论...
验证码 换一张
取 消