How to remove white spaces in Ruby with examples| delete leading and trail blank spaces

This tutorial explains how to remove whitespaces from a given string in Ruby.

  • How to strip whitespaces in a string?
  • How do remove from leading and trailing of a string?

How to remove white spaces at begin and end of a string

String strip method removes the whitespaces from the start and end of a string.

result=" welcome to my website ".strip
puts "-#{result}-"

Output:

-welcome to my website-

String lstrip method removes the whitespaces from starting a string.

result=" welcome to my website ".lstrip
puts "#{result}"
-welcome to my website -

String rstrip method removes the whitespaces from the end of a string.

result=" welcome to my website ".lstrip
puts "#{result}"
- welcome to my website-

How to strip whitespaces in a string?

delete method in a string removes all given parameters from a string and returns result string. Here is an example

result=" welcome to my website ".delete(" ")
puts "#{result}"

Output:

welcometomywebsite