rubyguides

String#squeeze

str.squeeze([other_str]*) -> string

The squeeze method returns a new string where runs of the same character are replaced with a single character. When called without arguments, it collapses all consecutive duplicate characters. When given one or more argument strings, it only squeezes those specific characters.

Syntax

string.squeeze
string.squeeze("character")
string.squeeze("char1", "char2")

Parameters

ParameterTypeDefaultDescription
other_strStringOptional. Characters to squeeze. If omitted, all consecutive duplicates are collapsed.

The optional arguments let you narrow the squeeze to a subset of characters, which is the key difference between "hello".squeeze and "hello".squeeze("l"). When no argument is given the method works on everything; when an argument string is supplied only those specific characters get collapsed.

Examples

Basic usage

# Squeeze all repeated characters
"hello  world".squeeze
# => "hello world"

# Multiple spaces become single space
"foo    bar".squeeze
# => "foo bar"

When called with no arguments, squeeze collapses every run of repeated characters in the text. That broad behaviour is useful for cleaning up accidental double letters or extra whitespace in one pass. When you know exactly which characters are noisy, passing them as arguments narrows the scope and preserves the rest of the input untouched.

With specific characters

# Only squeeze spaces
"hello  world".squeeze(" ")
# => "hello world"

# Only squeeze the letter "o"
"fooooobar".squeeze("o")
# => "foobar"

# Squeeze multiple specific characters
"aaa   bbb   ccc".squeeze("a", " ")
# => "ab ccc"

Targeting individual characters gives you precise control over which runs collapse and which stay as-is. In the last example above, only a and space get squeezed while the triple c passes through unchanged because it was not listed. That selective approach is what makes the method feel more deliberate than a blanket deduplication.

Practical examples

# Clean up user input with extra spaces
user_input = "   too   many     spaces   "
user_input.squeeze(" ")
# => " too many spaces"

# Remove repeated letters in word games
"bookkeeper".squeeze
# => "bokeper"

# Normalize whitespace in data
data = "line1\n\n\nline2\nline3"
data.squeeze("\n")
# => "line1\nline2\nline3"

The examples above show how squeeze handles three common real-world cases: user input with stray spaces, repeated letters in words, and normalised newlines in text data. In each scenario the method keeps the meaningful content intact while removing only the repetitive padding that the source picked up along the way. That makes it a reliable first choice when the noise consists of extra characters of the same kind.

Common Patterns

Input sanitization

def normalize_whitespace(text)
  text.squeeze(" \t\n")
end

normalize_whitespace("hello    world")
# => "hello world"

Wrapping squeeze in a helper method like normalize_whitespace makes the intent explicit at the call site. Instead of a bare method chain that a reader has to decode, the function name tells the story. When you are processing form data, log lines, or config values, that extra clarity pays off every time someone revisits the code.

Deduplicating characters

# Remove consecutive duplicates from any string
"aabbccddeeff".squeeze
# => "abcdef"

# Keep only unique consecutive characters
"1122334455".squeeze
# => "12345"

Deduplicating runs of the same character is useful in data cleaning and in small text puzzles where repeated letters are just noise. Because the method works on runs rather than positions, it handles strings of any length with the same predictable logic. When the goal is simply to collapse repeats, squeeze gives you a one-liner that reads almost like English.

Edge Cases

# Empty string returns empty
"".squeeze
# => ""

# Single character returns itself
"a".squeeze
# => "a"

# No repeated characters returns original
"abc".squeeze
# => "abc"

# Non-ASCII characters work correctly
"éééààà".squeeze
# => "éà"

Edge cases like empty strings, single characters, and non-ASCII input all return sensible results without special handling. That consistency means you can call squeeze inside a pipeline without adding guard clauses for unusual input shapes. The method degrades gracefully for every edge case shown here, so the surrounding code can stay focused on the main logic.

Error Handling

The squeeze method never raises an error. It handles all edge cases gracefully by returning appropriate values.

collapsing repeated characters carefully

squeeze is handy when repeated characters are just noise and the text should keep one clean copy of each run. That makes it useful for whitespace cleanup, simple normalization, and a few small text games where duplicate runs are not meaningful. Because the method can target specific characters or work on all of them, the call site can stay very explicit about what gets collapsed. That keeps the rule easy to read and the result easy to predict.

Staying focused on character runs rather than general matching is another strength. If the transformation needs to do more than collapse repeats, a different approach may give the reader a clearer picture of what is happening. For the narrow job of removing consecutive duplicates, though, squeeze keeps the logic short and direct.

Input cleanup is where the method really shines because the calling code can say exactly which repeated characters are acceptable and which ones should collapse. That makes the rule easy to test and easy to explain. When the goal is simply to smooth out repeated runs, squeeze keeps the shape of the original intact while removing the extra noise.

Small normalization steps are also a natural fit because the output still looks like the original text, just without the extra repetition. That makes it easier to read in examples than a more general substitution would be. The method keeps the intent narrow, which is often what you want when repeated characters are the only problem.

See Also