How to delete the leading and trailing whitespace of a string in 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: