All posts

How to delete the leading and trailing whitespace of a string in Ruby

 ruby

When programming, from time to time you will encounter strings in the format of " some leading whitespace" or "some trailing whitespace ". You can remove these spaces through the use of methods on the String object, lstrip and rstrip.

lstrip will delete all the whitespace characters that are present before the first non whitespace character in a string.

=> "  some leading whitespace".lstrip
"some leading whitespace"

rstrip will delete all the whitespace characters that are present after the last non whitespace character in a string.

=> "some trailing whitespace  ".rstrip
"some trailing whitespace"

To delete both the leading and trailing whitespace you can use the strip method.

=> "    some leading trailing whitespace  ".strip
"some leading trailing whitespace"

Further reading:

Postscript:

I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).