Ruby Tuesday – String#squeeze

Today’s Ruby Tuesday is on String#squeeze.

String#squeeze replaces runs of repeated characters in a source string down to a single character in the returned string.

"foo".squeeze
# => "fo"
"bar".squeeze
# => "bar"
"Mississippi".squeeze
# => "Misisipi"

String#squeeze can also take a string an argument. If a string is passed in, that string is seen as a set of characters to use for squeezing against the source string.

"Mississippi".squeeze("")
# => "Mississippi"
"Mississippi".squeeze("s")
# => "Misisippi"
"Mississippi".squeeze("abcprt")
# => "Mississipi"
"Mississippi".squeeze("sp")
# => "Misisipi"

If a string contains a - between two characters, that string is seen as containing a sequence of characters to include in the set of chacters to match for squeezing against the source string, but if it is first or last the - is seen as a character by itself.

"Mississippi".squeeze("a-r")
# => "Mississipi"
"Mississippi".squeeze("q-z")
# => "Misisippi"
"Mississippi".squeeze("pr-t")
# => "Misisipi"
"^^--~".squeeze('-~^')
# => "^-~"

If a string starts with a ^ then that string is seen as the negation of the set of characters that were given in that string to use, but if it is not the first character, then it is just seen as a normal ^ character.

"Mississippi".squeeze("^a-r")
# => "Misisippi"
"^^--~".squeeze('-^')
=> "^-~"

Backslashes can also be used to escape characters from any special meaning, but when using the backslash character in a double quoted string, then you have to make sure to escape that backslash with another backslash for it to be treated as an escape character in the string to String#squeeze.

"^^--~".squeeze('^')
# => "^--~"
"^^--~".squeeze("\^")
# => "^--~"
"^^--~~".squeeze('~-^')
# => "^-~"

String#squeeze doesn’t modify the source string given, but returns a new instance of a string for the result. If you do need to modify the string in place for some reason, there exists a String#squeeze! as well, but like many other Ruby methods that end in a !, if the original item is not modified a nil is returned.

str = "Mississippi"
# => "Mississippi"
str.squeeze
# => "Misisipi"
str
# => "Mississippi"
str.squeeze!
# => "Misisipi"
str
# => "Misisipi"
"bar".squeeze!
# => nil
"foo".squeeze!
# => "fo"

–Proctor