Ruby function to remove all white spaces?

What is the Ruby function to remove all white spaces? I'm looking for something kind of like PHP's trim()?


Solution 1:

If you want to remove only leading and trailing whitespace (like PHP's trim) you can use .strip, but if you want to remove all whitespace, you can use .gsub(/\s+/, "") instead .

Solution 2:

s = "I have white space".delete(' ')

And to emulate PHP's trim() function:

s = "   I have leading and trailing white space   ".strip

Solution 3:

Related answer:

"   clean up my edges    ".strip

returns

"clean up my edges"

Solution 4:

String#strip - remove all whitespace from the start and the end.

String#lstrip - just from the start.

String#rstrip - just from the end.

String#chomp (with no arguments) - deletes line separators (\n or \r\n) from the end.

String#chop - deletes the last character.

String#delete - x.delete(" \t\r\n") - deletes all listed whitespace.

String#gsub - x.gsub(/[[:space:]]/, '') - removes all whitespace, including unicode ones.


Note: All the methods above return a new string instead of mutating the original. If you want to change the string in place, call the corresponding method with ! at the end.