From: dblack@... Date: 2007-08-11T22:14:38+09:00 Subject: Re: Split a string based on change of character Hi -- On Sat, 11 Aug 2007, 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. Probably not better, but just for fun, here's a way using the strscan extension. I'd be very interested if anyone can get this to be less clunky -- in particular, the - [""] at the end. require 'strscan' s = StringScanner.new("AABCCCDAAAEE") s.string.split(//).inject([]) {|a,b| a << s.scan_until(/(?!#{b})/) } - [""] => ["AA", "B", "CCC", "D", "AAA", "EE"] David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)