Efficient String Compression in Ruby: A Step-by-Step Guide

Ruby @ Freshers.in

String compression is a fundamental operation in computer science, often used to reduce the size of data for efficient storage and transmission. In this article, we’ll explore how to write a Ruby function to perform basic string compression using the counts of repeated characters. We’ll also ensure that if the compressed string isn’t smaller than the original, we return the original string.

Understanding String Compression

String compression involves replacing repeated characters with a single character followed by the number of times it appears consecutively. For example, the string “aaabbbbcc” can be compressed to “a3b4c2”.

The Ruby Function

We’ll start by defining a Ruby function called compress_string to perform string compression.

def compress_string(input_str)
  compressed_str = ''
  count = 1

  (0...input_str.length).each do |i|
    if input_str[i] == input_str[i + 1]
      count += 1
    else
      compressed_str += input_str[i] + count.to_s
      count = 1
    end
  end

  return compressed_str.length < input_str.length ? compressed_str : input_str
end

Example Usage

Let’s explore some examples to see how our compress_string function works:

original_str_1 = "aaabbbbcc"
compressed_str_1 = compress_string(original_str_1)
puts "Original String: #{original_str_1}"
puts "Compressed String: #{compressed_str_1}"

Output:

Original String: aaabbbbcc
Compressed String: a3b4c2

In this example, “aaabbbbcc” gets successfully compressed to “a3b4c2.”

Another Example:

original_str_2 = "abcde"
compressed_str_2 = compress_string(original_str_2)
puts "Original String: #{original_str_2}"
puts "Compressed String: #{compressed_str_2}"

Output:

Original String: abcde
Compressed String: abcde

In this case, the compressed string is not smaller than the original, so the function returns the original string as required.

Get more useful articles on dbt
Author: user