James Gray
8/11/2007 4:24:00 PM
On Aug 11, 2007, at 8:14 AM, dblack@rubypal.com wrote:
> 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"]
My best effort:
>> require "strscan"
=> true
>> scanner = StringScanner.new("ZBBBCZZ")
=> #<StringScanner 0/7 @ "ZBBBC...">
>> char_runs = Array.new
=> []
>> char_runs << scanner.matched while scanner.scan(/(.)\1*/m)
=> nil
>> char_runs
=> ["Z", "BBB", "C", "ZZ"]
James Edward Gray II