2011-04-01 120 views
9

我的字符串:分割字符串轉換成數字陣列

>> pp params[:value] 
"07016,07023,07027,07033,07036,07060,07062,07063,07065,07066,07076,07081,07083,07088,07090,07092,07201,07202,07203,07204,07205,07206,07208,07901,07922,07974,08812,07061,07091,07207,07902" 

這怎麼能成爲獨立的數字像數組:

["07016", "07023", "07033" ... ] 
+0

你應該放棄的字符串。寫'params [:value]'與這個問題無關,並且是誤導性的。 – sawa 2011-04-01 17:00:20

回答

33
result = params[:value].split(/,/) 

串#分裂是你所需要的

12

嘗試this

arr = "07016,07023,07027".split(",") 
6

請注意,您所要求的不是一個單獨數字的數組,而是一串看起來像數字的字符串。正如其他人所指出的,你可以得到與:

arr = params[:value].split(',') 

# Alternatively, assuming integers only 
arr = params[:value].scan(/\d+/) 

如果你真的想要的數字(整數)的數組,你可以做到這一點,像這樣:

arr = params[:value].split(',').map{ |s| s.to_i } 

# Or, for Ruby 1.8.7+ 
arr = params[:value].split(',').map(&:to_i) 

# Silly alternative 
arr = []; params[:value].scan(/\d+/){ |s| arr << s.to_i }