2009-11-20 73 views
0

我只是想這樣一個字符串轉換:轉換未格式化的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

的字符串split方法將很好地做到:

str.split(' ')

1

陣列= str.split

+0

糟糕,誤讀的問題。現在正確。 – Ben 2009-11-20 21:58:51

0

潛在感興趣的還有:

arr = %w{tree dog orange music apple}