On Tue, Dec 13, 2011 at 11:08 AM, Adit Cahya Ramadhan Adit
<matematika.adit / gmail.com> wrote:
> 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?

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. :-)

Cheers

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/