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"]
["4.", "ARTHUR"]
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? }