programming-examples/ruby/Data_Structures/basic_string_compression.rb
2019-11-15 12:59:38 +01:00

24 lines
352 B
Ruby

def compress_string(str)
result = []
prev = str[0]
count = 0
str.each_char do |char|
if char == prev
count += 1
else
result << char + count.to_s
prev = char
count = 0
end
end
result << char + count.to_s
result = result.join('')
if result.length < str.length
result
else
str
end
end