ruby - 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"]

4 Answers: 

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? }

Why not just do

irb(main):004:0> word = "4.ARTHUR"
=> "4.ARTHUR"
irb(main):005:0> word.split('.')
=> ["4", "ARTHUR"]

When you want to split up a string but keep all of its parts, String#scan is often a better fit than String#split:

word = "4.ARTHUR"
# => ["4.", "ARTHUR"]

See it on


Try this

a, b = word.match(/^(\d+\.)?(.*)/).captures

The split method is meant to be used with a separator, as for example a comma. What you are doing is splitting the string into two parts without a separator, just use capture groups.