ScottW
ScottW

Reputation: 431

Split a string into an array based on runs of contiguous characters

I've been searching for an answer to this in Ruby for a little while now and haven't found a good solution. What I am trying to figure out is how to split a string when the next character doesn't match the previous and pass the groupings into an array. ie.

'aaaabbbbzzxxxhhnnppp'

becomes

['aaaa', 'bbbb', 'zz', 'xxx', 'hh', 'nn', 'ppp']

I know I could just iterate over each char in the string and check for a change but am curious if there's anything built-in that could tackle this in a elegant manner.

Upvotes: 1

Views: 911

Answers (1)

Tonttu
Tonttu

Reputation: 1821

Doable with a simple regex:

'aaaabbbbzzxxxhhnnppp'.scan(/((.)\2*)/).map{|x| x[0]}
=> ["aaaa", "bbbb", "zz", "xxx", "hh", "nn", "ppp"]

Upvotes: 5

Related Questions