0

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?

4
  • array of strings you have ? Commented Apr 23, 2014 at 12:49
  • 2
    Is this work - 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] 2.1.0 :004 > Commented Apr 23, 2014 at 12:52
  • 2
    It can be parsed as JSON, too: JSON.parse(string).map(&:to_i) Commented Apr 23, 2014 at 12:53
  • @Stefan Humm...Right, +1 Commented Apr 23, 2014 at 12:54

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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] 

Comments

1

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

2 Comments

would someone please edit and explain the answer? This is part of our guidelines for a minimum-quality answer.
I think Uri already provided a decent resolution and the method names should be self explanatory. Thanks @Stefan for the edit though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.