将未格式化的对象字符串转换为数组

时间:2009-11-20 21:56:03

标签: ruby string

我只想转换一个这样的字符串:

str = "tree dog orange music apple"

进入这样的数组:

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

我尝试沿着这样的道路前行,然后才意识到这是一个死胡同:

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

非常感谢任何帮助。谢谢!

3 个答案:

答案 0 :(得分:3)

String split方法可以很好地完成:

str.split(' ')

答案 1 :(得分:1)

array = str.split

答案 2 :(得分:0)

也有潜在的兴趣:

arr = %w{tree dog orange music apple}