From: Logan Capaldo Date: 2007-08-14T07:36:11+09:00 Subject: Re: Split a string based on change of character ------=_Part_31415_15891150.1187044575122 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On 8/13/07, Brad Phelan wrote: > > 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 {$&} What's wrong with s.enum_for(:scan, /(.)\1*/).map { $& } ? -- > Brad Phelan > http://xtargets.com > > ------=_Part_31415_15891150.1187044575122--