Reputation: 65
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!
Upvotes: 0
Views: 47
Reputation: 118271
I would do
array = [ 'c32860:x:3105:dputnam,kmathise,hhoang3,nhalvors,jchildre\n' ]
array[0].scan(/(?<=:)?\w+(?=[,\\n])/)
# => ["dputnam", "kmathise", "hhoang3", "nhalvors",'jchildre' ]
Upvotes: 0
Reputation: 2236
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"]
Upvotes: 1
Reputation: 160863
Below will give you the expected result:
array2 = array[0].split(':').last.gsub(/\\n\Z/, '').split(',')
Upvotes: 0