"aaabbccccdadd" => [ [a, 3], [b, 2], [c, 4], [d, 1], [a, 1], [d, 2] ]

I’m thinking to translate string to an array like this:
“aaabbccccdadd” => [ [a, 3], [b, 2], [c, 4], [d, 1], [a, 1], [d, 2] ]

this is my code:

ary = []
“aaabbccccdadd”.scan(/((.)\2*)/){ |a,b| ary << [b, a.size] }

ary #=> [[“a”, 3], [“b”, 2], [“c”, 4], [“d”, 1], [“a”, 1], [“d”, 2]]

But, I wonder if there are more effective or beautiful solution than
this.
How do you think?

you can use the enumerator form of scan (ruby1.9):

“aaabbccccdadd”.scan(/((.)\2*)/).map { |a,b| [b, a.size] }

martin

On Tue, Dec 13, 2011 at 2:08 AM, Adit Cahya Ramadhan Adit

On Tue, Dec 13, 2011 at 4:08 AM, Adit Cahya Ramadhan Adit <
[email protected]> wrote:

But, I wonder if there are more effective or beautiful solution than
this.
How do you think?


Posted via http://www.ruby-forum.com/.

Anyone else look at String#squeeze and get sad that it didn’t take a
block?

One day… one day I will use you, String#squeeze -.^

On Tue, Dec 13, 2011 at 11:08 AM, Adit Cahya Ramadhan Adit
[email protected] wrote:

But, I wonder if there are more effective or beautiful solution than
this.
How do you think?

Hm…

irb(main):008:0> ary = “aaabbccccdadd”.to_enum(:scan,
/(.)\1*/).map{|a,| [a, $&.length]}
=> [[“a”, 3], [“b”, 2], [“c”, 4], [“d”, 1], [“a”, 1], [“d”, 2]]

irb(main):013:0> ary = “aaabbccccdadd”.scan(/((.)\2*)/).map {|a,b| [b, a.length]}
=> [[“a”, 3], [“b”, 2], [“c”, 4], [“d”, 1], [“a”, 1], [“d”, 2]]

Only marginally nicer.

Btw.

irb(main):018:0> “aaabbccccdadd”.gsub(/(.)\1+/){|m| m[0]+m.length.to_s}
=> “a3b2c4dad2”

RLE for Characters. :slight_smile:

Cheers

robert