How do i split this string.
\"6885558 8866887777\" => [\"6\", \"88\", \"555\", \"8\", \"88\", \"66\", \"88\", \"7777\"]
I tried this, b
split
will just use whatever it matches as a delimiter, removing it from the string in question. What you're looking for is scan:
str = "6885558 8866887777"
str.scan(/((\d)\2*)/).map(&:first)
# => ["6", "88", "555", "8", "88", "66", "88", "7777"]
Taking it slow, the \d
matches any digit. It's in the second capturing group, so \2*
then matches any further occurrences of the same digit. This produces an array that looks like
[["6", "6"], ["88", "8"], ["555", "5"], ["8", "8"],
["88", "8"], ["66", "6"], ["88", "8"], ["7777", "7"]]
Since we only want the first item in each of those sub arrays, we can collect them all with map(&:first)
.
(Note that str.scan(/(\d)\1*/)
would simply produce an array out of the first capturing group, which means we'd only get one digit from a sequence of possibly repeated numbers.)