In Ruby, you can remove all whitespace characters from a string by using the gsub
method with a regular expression.
Here's an example of how to remove all whitespace characters from the string "the quick brown fox jumps over the lazy dog":
main.rb78 chars3 lines
In this example, the gsub
method is used with the regular expression /\s+/
to match one or more whitespace characters. The replacement string is an empty string ""
, effectively removing all whitespace characters from the original string.
After executing this code, the value of the str
variable will be:
main.rb38 chars2 lines
So, all the whitespace characters have been removed.
Note that the original string cannot be modified directly because strings in Ruby are immutable. Therefore, we need to assign the result of gsub
to a new or the same variable to store the modified string.
gistlibby LogSnag