How to remove recurring or duplicate character(s) in Ruby

Overview

Removing recurring characters in a string is easy to do in Ruby. We use the squeeze() method. The squeeze() method returns a new string with identical characters reduced to a single character.

The squeeze() method can take an optional parameter. The parameter could be a string, character, or regular expression. When the parameter is passed to this method, every consecutive instance of the parameter present in the string will be squeezed into one instance.

Syntax

str.squeeze([other_str])

Parameters

str: This is the string upon which we want to call the squeeze() method.

other_str: This is an optional parameter. It is a string, character, or regular expression which will be removed.

Return value

A new string is returned with recurring characters changed to one instance. If a parameter is passed and is recurring in the string, it will be replaced by one instance.

Code example

# create some strings
str1 = "wellccomme"
str2 = "too"
str3 = "Ruubbyy"
# squeeze strings and printing them
puts str1.squeeze()
puts str2.squeeze()
puts str3.squeeze()

Explanation

  • Lines 2 to 4: We create some strings and initialize them with some values.

  • Lines 7 to 9: The squeeze() method is called on the strings we create. Then, we print them.

Code example

# crete a string
str1 = "welommme to edpresso"
str2 = "welcomme toooo edpresso"
# squeeze methods
puts str1.squeeze("m")
puts str2.squeeze("o")

Explanation

  • Lines 2 and 3: We create a string, str1, and initialize it with a value.
  • Line 6: We pass "m" as a parameter to the squeeze() method to make any recurring character, "m", one. Then we print the value.
  • Line 7: We pass "o" as a parameter to the squeeze() method to make any recurring character, "o", one. Then, we print the value.

Free Resources