How to remove leading and trailing whitespace in a string in Ruby
Whitespace refers to any of the following characters:
- Null
- Horizontal tab
- Line feed
- Vertical tab
- Form feed
- Carriage return
- Space
The strip method is used to remove any of these characters, whether leading or trailing, from a string.
Syntax
str.strip
where str is the string we want to remove whitespace characters from.
Parameters
This method doesn’t take any parameters.
Return value
This method returns a string str but with all whitespace characters removed.
Code
# create some stringsstr1 = "\tEdpresso"str2 = "\n\f\vis"str3 = " awesome "# remove whitespacea = str1.stripb = str2.stripc = str3.strip# print resultsputs aputs bputs c
Explanation
-
Lines 2-4: We have strings that contain whitespace characters.
-
Lines 7-9: We use the
stripmethod to remove any whitespace characters and store the results in variablesa,b, andc. -
Lines 12-14: We print our results to the console.