From: Brad Phelan Date: 2007-08-13T19:20:00+09:00 Subject: Re: Split a string based on change of character Andrew Savige wrote: > For a string "ZBBBCZZ", I want to produce a list ["Z", "BBB", "C", "ZZ"] > That is, break the string into pieces based on change of character. > > Though this works: > > s = "ZBBBCZZ" > x = s.scan(/((.)\2*)/).map {|i| i[0]} Another variant which gets rid of one of the capture groups and does introduce an artificial split character Enumerator.new(s, :scan, /(.)\1*/).map {$&} Note the $& will not work in the example > x = s.scan(/((.)\2*)/).map {|i| i[0]} because the map is run on an array after the scan has happened. To run the map inline with the scan you need the Enumerator object. I doubt using Enumerator is any faster though. Wouldn't it be nicer if scan returned an enumerable instead of an array. We could define class String def scan_enum regexp Enumerator.new self, :scan, regexp end end and then be able to do s.scan_enum(/(.)\1*/).map {$&} -- Brad Phelan http://xtargets.com