Dave Dave - 4 years ago 109
Ruby Question

How do I split on a regex and get my elements into an array?

I'm using Ruby 2.4. Is there any way I can split on a regex and get the resulting elements in an array? I thought this was the way

2.4.0 :003 > word = "4.ARTHUR"
=> "4.ARTHUR"
2.4.0 :004 > word.split(/^\d+\./)
=> ["", "ARTHUR"]

but as you see, the first element of my array is an empty string despite the fact that the pattern matches. I would like the output to be

["4.", "ARTHUR"]

Answer Source

Note that split splits the string where a match is found. So, ^\d+\. matches 4. in 4.ARTHUR at the beginning and thus, the result is an empty string (the beginning of the string) and ARTHUR. To keep the match obtained during split operation with a regex, you need to wrap the whole pattern with a capturing group and to get rid of the empty items, you can just remove them later:

word.split(/^(\d+\.)/).reject { |x| x.empty? }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download