How to empty a string in Ruby

Overview

Emptying a string in Ruby is done with the clear method.

It makes a string empty and returns an empty space.

Syntax

str.clear

Parameters

The clear method does not take any parameters, but it clears the contents of the string it is called upon.

Return value

Nothing is returned after a string has been emptied with the clear method.

Example

In the example below, we will create some strings and call the clear method on them.

# create some strings
str1 = "welcome"
str2 = "to"
str3 = "Edpresso"
# empty the strings
str1.clear
str2.clear
str3.clear
# print empty strings
puts str1
puts str2
puts str3

Explanation

In the code above:

  • Lines 1-4: We create three strings str1, str2, and str3.
  • Lines 7-9: We call the clear method on str1, str2, and str3.
  • Lines 12-14: We print str1, str2, and str3. As we can see, the strings are returned as empty, as the code has cleared all the content in the strings.

Free Resources