简体   繁体   中英

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. 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?

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:

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.

Here is my try using 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.
2) splits resulting string on commas
3) map strings to integers and return the resulting array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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