简体   繁体   English

在Ruby中将字符串拆分为数组

[英]Split string looking as array to array in Ruby

I have string ["10000", "10001"] (please do not ask why it is string, I am fixing errors after one dude...) and now I have got problem with spliting each number as separate item, so for example I would like to have array like: [10000, 10001] , but I have big problem with writing proper RegExp. 我有字符串["10000", "10001"] (请不要问为什么它是字符串,我正在纠正一个家伙之后的错误...),现在我遇到了将每个数字拆分为单独项目的问题,例如我想使用类似[10000, 10001]数组,但是编写适当的RegExp时遇到了很大的问题。 Now I am doing so: 现在我正在这样做:

items.gsub(/[^\d]/, '').scan(/./).each do |collection_id|
  my code here
end

which works with 1 digit ids, but not multi :-(. Could you help me please? 可以使用1位数的ID,但不能使用多:-(.。能帮我吗?

string = '["10000", "10001"]'
string.scan(/\d+/).map(&:to_i)
# => [10000, 10001] 

Explanation 说明

.scan(/d+/) method returns an array of all the character blocks containing only digits: .scan(/d+/)方法返回一个仅包含数字的所有字符块的数组:

string.scan(/\d+/)
# => ["10000", "10001"]

.map(&:to_i) executes the method .to_i on each element in the resulting array, and creates a new array from the results. .map(&:to_i)在结果数组中的每个元素上执行方法.to_i ,并根据结果创建一个新数组。

Here is my try using YAML : 这是我使用YAML尝试:

2.1.0 :001 > string = '["10000", "10001"]'
 => "[\"10000\", \"10001\"]" 
2.1.0 :002 > require 'yaml'
 => true 
2.1.0 :003 > YAML.load(string).map(&:to_i)
 => [10000, 10001] 

You may try this: 您可以尝试以下方法:

"[\"10000\", \"10001\"]".gsub(/\[|\]|"/, '').split(",").map{ |s| s.to_i }

It: 它:
1) replaces the characters [, ] and " with empty string. 1)用空字符串替换字符[,]和“。
2) splits resulting string on commas 2)在逗号上分割结果字符串
3) map strings to integers and return the resulting array 3)将字符串映射为整数并返回结果数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM