From: Jeremy Hinegardner Date: 2007-08-11T18:12:57+09:00 Subject: Re: Split a string based on change of character On Sat, Aug 11, 2007 at 09:52:24AM +0900, 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]} > > I'm new to Ruby and am interested to learn if there is a better way to > do it. > > BTW, in Python, it can be done with a regex (similar to above) or via > their itertools library: > > import itertools > s = "ZBBBCCZZ" > x = [''.join(g) for k, g in itertools.groupby(s)] > > Does anyone know if Ruby has a similar library to Python's itertools? Nothing off the top of my head, but how does this work for you ? in_str.split('').inject([]) do |m,l| if m.last and m.last[0].chr == l m[-1] += l else m << l end m end Its not too lines, but it will return the same array enjoy -jeremy -- ======================================================================== Jeremy Hinegardner jeremy@hinegardner.org