Ruby-on-rails 将字符串拆分为数字数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5513556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:49:18  来源:igfitidea点击:

Split a string into an array of numbers

ruby-on-railsruby

提问by Trip

My string:

我的字符串:

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

How can this become an array of separate numbers like :

这如何成为一个单独数字的数组,例如:

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

回答by Matt Greer

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

String#split is what you need

String#split 正是你所需要的

回答by Jonas Elfstr?m

Try this:

试试这个

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

回答by Phrogz

Note that what you ask for is not an array of separate numbers, but an array of strings that look like numbers. As noted by others, you can get that with:

请注意,您要求的不是一个单独的数字数组,而是一个看起来像数字的字符串数组。正如其他人所指出的,您可以通过以下方式获得:

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

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

If you actually wanted an array of numbers (Integers), you could do it like so:

如果你真的想要一个数字数组(整数),你可以这样做:

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 }