Reputation: 673
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?
Upvotes: 0
Views: 80
Reputation: 37409
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.
Upvotes: 4
Reputation: 1340
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
Upvotes: 1
Reputation: 118289
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]
Upvotes: 1