Emptying a string in Ruby is done with the clear
method.
It makes a string empty and returns an empty space.
str.clear
The clear
method does not take any parameters, but it clears the contents of the string it is called upon.
Nothing is returned after a string has been emptied with the clear
method.
In the example below, we will create some strings and call the clear
method on them.
# create some stringsstr1 = "welcome"str2 = "to"str3 = "Edpresso"# empty the stringsstr1.clearstr2.clearstr3.clear# print empty stringsputs str1puts str2puts str3
In the code above:
str1
, str2
, and str3
.clear
method on str1
, str2
, and str3
.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.