Ruby String Encode Consecutive Letter Frequency
ruby
Solution
"aaabbcbbaaa".scan(/((.)\2*)/).map{|s, c| [c, s.length]}
Problem
I want to encode a string in Ruby such that output should be in pairs so that I could decode it. I want to encode in such a way that each pair contains the next distinct letter in the string, and the number consecutive repeats. e.g If I encode "aaabbcbbaaa" output should [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]] here is the code. ``` def encode( s ) b = 0 e = s.length - 1 ret = [] while ( s <= e ) m = s.match( /(\w)\1*/ ) l = m[0][0] n = m[0].length ret << [l, n] end ret end ```