0

I have an array with a single element shown below:

array = [ 'c32860:x:3105:dputnam,kmathise,hhoang3,nhalvors,jchildre\n' ]

I want to create a new array that looks like this:

array2 = [ 'dputnum', 'kmathise', 'hhoang3', 'nhalvors', 'jchildre' ]

How would I accomplish this using Ruby and/or regex in a fairly clean way? I'm very new to programming and I did a bunch of ghetto things such as array-to-string-back-to-array conversions, .reverse.chomp.reverse shenanigans, and still could not end up with the result I wanted. Help appreciated!

3 Answers 3

1

Try scan with a regexp:

array = [ 'c32860:x:3105:dputnam,kmathise,hhoang3,nhalvors,jchildre\n' ]
array = array.first.scan(/:?(\w+)[,\\n]/).flatten

p array
#=> ["dputnam", "kmathise", "hhoang3", "nhalvors", "jchildre"]
Sign up to request clarification or add additional context in comments.

Comments

0

Below will give you the expected result:

array2 = array[0].split(':').last.gsub(/\\n\Z/, '').split(',')

Comments

0

I would do

array = [ 'c32860:x:3105:dputnam,kmathise,hhoang3,nhalvors,jchildre\n' ]
array[0].scan(/(?<=:)?\w+(?=[,\\n])/)
# => ["dputnam", "kmathise", "hhoang3", "nhalvors",'jchildre' ]

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.