Ruby String Trim Whitespace
We can define strings as a sequence of one or more characters. The characters can include letters, numbers, or special symbols. In Ruby, we identify strings by enclosing them in single (“) or double (“”) quotation marks.
Unlike other programming languages, strings in Ruby are mutable objects allowing you to replace a string instead of initializing a new one.
Today’s guide will look at working with strings and terminating whitespace characters in a Ruby string.
Let’s get into it.
Creating Strings in Ruby
As mentioned, we create a string by enclosing them in single or double-quotes. Both methods are valid, and the Ruby interpreter will recognize them as valid Ruby strings.
str2 = "I am @str1ng"
Escape characters allow for adding extra meaning to a string in Ruby. For example, suppose we want to add quotation marks to a string.
By default, Ruby will interpret the trailing quotes as the end of a string leading to an error.
In this example, the second quotation will cause an error. Although we can use double quotes and single quotes to prevent this error, we can use escape characters.
To escape the second quote, we can use a backslash symbol (\)
Ruby will ignore the trailing character and treat it as part of the string in such a case.
The same case applies to double-quotes. Other escape characters include:
- \\ – single backslash
- \a – alert
- \t – Tab
- \r – Carriage return
- \s – Space
- \b – backspace
- \n – newline
Let us now focus on how to remove whitespace from a string in Ruby.
Method 1: Strip
The first method we can use to remove whitespaces in a string is the strip method. This method returns a copy of the input string with all whitespace characters removed.
Whitespace characters include null, tab, vertical form, carriage return, and space.
puts " \r\n second\n ".strip # -> second
puts "\f\v\r\n\t third".strip # - third
As in the example above, the strip method will remove all whitespace characters in the specified string.
The strip method does not alter the original string. It only returns a copy of the string with the whitespaces removed. If we want to apply the changes to the strings, we can use the strip! method.
str = str.strip!
The example program will show an output similar to the one shown below:
Method 2: Delete
If you only want to remove spaces from the string, you can use the delete method. For example:
This should return the string with the spaces removed.
NOTE: If you are using other whitespace characters, you will need to specify the explicitly as:
Method 3: gsub
Gsub is a predefined string method in Ruby. It returns a copy of the specified string with specified pattern occurrences. The pattern specified in the gsub method is in the form of a regular expression.
To remove whitespaces using the gsub method:
This guide covered how to work with strings and various methods you can use to remove whitespace characters from a string.