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.
str.squeeze([other_str])
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.
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.
# create some stringsstr1 = "wellccomme"str2 = "too"str3 = "Ruubbyy"# squeeze strings and printing themputs str1.squeeze()puts str2.squeeze()puts str3.squeeze()
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.
# crete a stringstr1 = "welommme to edpresso"str2 = "welcomme toooo edpresso"# squeeze methodsputs str1.squeeze("m")puts str2.squeeze("o")
str1
, and initialize it with a value."m"
as a parameter to the squeeze()
method to make any recurring character, "m"
, one. Then we print the value."o"
as a parameter to the squeeze()
method to make any recurring character, "o"
, one. Then, we print the value.