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!

ayaz15m
  • 25
  • 1
  • 1
  • 4

2 Answers2

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

should do it.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
  • 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) –  May 03 '15 at 05:49
  • @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. – Cary Swoveland May 03 '15 at 06:08
1

You can also use this non-regex solution:

"{1,22,33,444}".delete("{}").split(",")
  #=> ["1", "22", "33", "444"]
Sid
  • 2,683
  • 18
  • 22
  • A variant of your approach: `"{1,22,33,444}".split(/[{,}]/)[1..-1] #=> ["1", "22", "33", "444"]`. – Cary Swoveland May 03 '15 at 03:12
  • Wow. Never knew that two strings literals next to each other on a line would be concatinated! Nice! –  May 03 '15 at 05:44
  • @jphager2, see the accepted answer [here](http://stackoverflow.com/questions/18193792/where-is-rubys-string-literal-juxtaposition-feature-officially-documented/18194632#18194632) for more on that. If memory serves, it comes from C/C++. Here Sid could have just written `delete("{}")`. – Cary Swoveland May 03 '15 at 06:26
  • 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. –  May 03 '15 at 06:37
  • @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"? – Sid May 03 '15 at 06:44
  • @Sid, that's very curious indeed. I suggest you dig into it. Maybe you will have the honour of reporting a genuine Ruby bug. btw, I get the same results as you with v2.2. – Cary Swoveland May 03 '15 at 07:43
  • @CarySwoveland ok figured it out, its not a bug - it takes the intersection of the outputs of each argument you pass in. Since "hello".delete "lo" is "he" and "hello".delete "l" is "heo" it will output "heo" if you pass in both "lo" and "l" irrespective of the order you pass them in. – Sid May 03 '15 at 08:02
  • Excellent! You've explained the behavior, but what is your basis for concluding its not a bug? (Bugs in Ruby are very rare, of course.) Is "intersection" the right word? – Cary Swoveland May 03 '15 at 09:00