To remove all whitespace characters from a string in Ruby, you can use the `gsub` method with a regular expression pattern.
In this example,
str
with a value of "Hello World"
.gsub
method with a regular expression pattern /\s/
to replace all whitespace characters with an empty string.str
.str = "Hello World"
modified_str = str.gsub(/\s/, "")
puts "Modified string: #{modified_str}"
Modified string: HelloWorld
In this example,
str
with a value of "apple\tbanana\n cherry "
.gsub
method with a regular expression pattern /\s/
to replace all whitespace characters with an empty string.str
.str = "apple\tbanana\n cherry "
modified_str = str.gsub(/\s/, "")
puts "Modified string: #{modified_str}"
Modified string: applebananacherry
In this tutorial, we learned How to Remove All Whitespace Characters from a String in Ruby language with well detailed examples.