将字符串拆分为数字数组

时间:2011-04-01 12:46:21

标签: ruby-on-rails ruby

我的字符串:

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

3 个答案:

答案 0 :(得分:34)

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

String#split是你需要的

答案 1 :(得分:13)

尝试this

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

答案 2 :(得分: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 }