String#squeeze

str.squeeze([other_str]*) -> string
Returns: String · Updated March 13, 2026 · String Methods
strings characters compression cleanup

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.

Examples

Basic usage

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

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

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"

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"

Common Patterns

Input sanitization

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

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

Deduplicating characters

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

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

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
# => "éà"

Error Handling

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

See Also