compress_str

ahmadabdelhalim · @ahmadabdelhalim · almost 4 years

a function that accepts a string as an argument, and returns a new string where streaks of consecutive characters are compressed. For example “aaabbc” is compressed to “3a2bc”.

def compress_str(str)
new_str = ""
i = 0
while i < str.length
char = str[i]
count = 0
while char == str[i]
count += 1
i += 1
end
if count > 1
new_str += count.to_s + char
else
new_str += char
end
end
new_str
end
2 · 1 · 0