0

I have the array of string like,

a = ["13", "---\n- '5'\n- 19\n- 20\n", "---\n- 21\n", "---\n- 21\n- 22\n", "---\n- 21\n- 22\n"]

but i want converted array like,

a = ["13","5,19,20","21","21,22","21,22"]

I have already tried Regexp and gsub, but i didn't get array as i want. Please help if any one know.

7
  • post the gsub command you tried. Commented Dec 11, 2014 at 8:14
  • any negatives in the data? Commented Dec 11, 2014 at 8:25
  • @AvinashRaj In loop i was doing like this b << c.gsub(/[^0-9]/,' ').strip and as output i.e ["13", "5 19 20", "21", "21 22", "21 22"]. But i got answer from shivam. Commented Dec 11, 2014 at 8:28
  • Are you trying to parse a YAML file? Commented Dec 11, 2014 at 9:30
  • @Stefan No i am getting this data from database not from YAML file. Commented Dec 11, 2014 at 12:30

2 Answers 2

2

Regex scanning for integers and joining them with ,

a = ["13", "---\n- '5'\n- 19\n- 20\n", "---\n- 21\n", "---\n- 21\n- 22\n", "---\n- 21\n- 22\n"]
a.map{|b| b.scan(/\d+/).join(',')}
# => ["13", "5,19,20", "21", "21,22", "21,22"]

Note: Assuming no negatives in input array (as asked in a comment)

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

3 Comments

you can use /-?\d+/ to include the negatives as well
@xlembouras yup we can use that as well. Thanks for your suggestion.
@xlembouras and avinash thanks for adding more value to my answer. +1
1

You could also do it by joining, using gsub, then splitting and formating:

a.join(',').gsub(/[^\d,]/, ' ').split(',').map { |s| s.split.join(',') }
  #=> ["13", "5,19,20", "21", "21,22", "21,22"]

Comments

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.