remove all white space in ""the quick brown fox jumps over the lazy dog"" in ruby

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.rb
str = "the quick brown fox jumps over the lazy dog"
str = str.gsub(/\s+/, "")
78 chars
3 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.rb
"thequickbrownfoxjumpsoverthelazydog"
38 chars
2 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.

related categories

gistlibby LogSnag