Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
character
string
squeeze()
communitycreator

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

okwudili onyejiaku

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()
Change recurring characters to one in a string in Ruby

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")
Change recurring characters in a string in Ruby

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.

RELATED TAGS

ruby
character
string
squeeze()
communitycreator
RELATED COURSES

View all Courses

Keep Exploring