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 strings
str1 = "\tEdpresso"
str2 = "\n\f\vis"
str3 = " awesome "
# remove whitespace
a = str1.strip
b = str2.strip
c = str3.strip
# print results
puts a
puts b
puts c

Explanation

  • Lines 2-4: We have strings that contain whitespace characters.

  • Lines 7-9: We use the strip method to remove any whitespace characters and store the results in variables a, b, and c.

  • Lines 12-14: We print our results to the console.