2.30. Removing Duplicate Characters

Runs of duplicate characters may be removed using the squeeze method:

s1 = "bookkeeper"
s2 = s1.squeeze         # "bokeper"
s3 = "Hello..."
s4 = s3.squeeze         # "Helo."
If a parameter is specified, only those characters will be squeezed.
s5 = s3.squeeze(".")    # "Hello."

This parameter follows the same rules as the one for the count method (see the section 2.28, “Counting Characters in Strings” earlier in this chapter); that is, it understands the hyphen and the caret.

There is also a squeeze! method.

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.