Removing all whitespace from a string in Ruby

You can use something like:

var_name.gsub!(/\s+/, '')

Or, if you want to return the changed string, instead of modifying the variable,

var_name.gsub(/\s+/, '')

This will also let you chain it with other methods (i.e. something_else = var_name.gsub(...).to_i to strip the whitespace then convert it to an integer). gsub! will edit it in place, so you'd have to write var_name.gsub!(...); something_else = var_name.to_i. Strictly speaking, as long as there is at least one change made,gsub! will return the new version (i.e. the same thing gsub would return), but on the chance that you're getting a string with no whitespace, it'll return nil and things will break. Because of that, I'd prefer gsub if you're chaining methods.

gsub works by replacing any matches of the first argument with the contents second argument. In this case, it matches any sequence of consecutive whitespace characters (or just a single one) with the regex /\s+/, then replaces those with an empty string. There's also a block form if you want to do some processing on the matched part, rather than just replacing directly; see String#gsub for more information about that.

The Ruby docs for the class Regexp are a good starting point to learn more about regular expressions -- I've found that they're useful in a wide variety of situations where a couple of milliseconds here or there don't count and you don't need to match things that can be nested arbitrarily deeply.

As Gene suggested in his comment, you could also use tr:

var_name.tr(" \t\r\n", '')

It works in a similar way, but instead of replacing a regex, it replaces every instance of the nth character of the first argument in the string it's called on with the nth character of the second parameter, or if there isn't, with nothing. See String#tr for more information.


You could also use String#delete:

str = "123\n12312313\n\n123 1231 1231 1"

str.delete "\s\n"
  #=> "12312312313123123112311"

You could use String#delete! to modify str in place, but note delete! returns nil if no change is made