0

I converted my db and the data in one of my tables got changed in the conversion. Basically, I want to go from: "{1,2}" to ["1", "2"] in ruby. Any thoughts?

Also, it wont be just two numbers always, it will vary for each row in the table.

Thanks in advance!

0

2 Answers 2

3
"{1,22,33,444}".scan(/\d+/) #=> ["1", "22", "33", "444"]

should do it.

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

2 Comments

Just have to watch out for the "number's" type. The OP didn't specify that it would be necessarily Integers (though it probably would be)
@jphager2, That's true, but the example and reference to "just two numbers" suggested natural numbers to me. If the strings to be captured can be something other than natural numbers, a different regex would of course be required.
1

You can also use this non-regex solution:

"{1,22,33,444}".delete("{}").split(",")
  #=> ["1", "22", "33", "444"]

8 Comments

A variant of your approach: "{1,22,33,444}".split(/[{,}]/)[1..-1] #=> ["1", "22", "33", "444"].
Wow. Never knew that two strings literals next to each other on a line would be concatinated! Nice!
@jphager2, see the accepted answer here for more on that. If memory serves, it comes from C/C++. Here Sid could have just written delete("{}").
Thanks for the link. I guess in the end I did know about it, because I've used it through continued lines using '\' but never thought about it.
@CarySwoveland Thanks for pointing that out, I've edited my answer. Looking back at the ruby docs for #delete method on strings, one thing I dont understand is why "hello".delete("lo","l") returns "heo". Do you know why it acts that way because I would think that it should return "he" as it first deletes "lo" and then "l"?
|

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.