Removing all whitespace from a string in Ruby -
how can remove newlines , spaces string in ruby?
for example, if have string:
"123\n12312313\n\n123 1231 1231 1"
it should become this:
"12312312313123123112311"
that is, whitespaces should removed.
you can use like:
var_name.gsub!(/\s+/, '')
or, if want return changed string, instead of modifying variable,
var_name.gsub(/\s+/, '')
this let chain other methods (i.e. something_else = var_name.gsub(...).to_i
strip whitespace convert integer). gsub!
edit in place, you'd have write var_name.gsub!(...); something_else = var_name.to_i
.
gsub
works replacing matches of first argument contents second argument. in case, matches sequence of consecutive whitespace characters (or single one) regex /\s+/
, replaces empty string. there's block form if want processing on matched part, rather replacing directly; see string#gsub
more information that.
the ruby docs class regexp
starting point learn more regular expressions -- i've found they're useful in wide variety of situations you're okay without incredibly fast code, or if don't need match things can nested arbitrarily deeply.
as gene suggested in comment, use tr
:
var_name.tr(" \t\r\n", '')
it works in similar way, instead of replacing regex, replaces every instance of nth character of first argument in string it's called on nth character of second parameter, or if there isn't, nothing. see string#tr
more information.
Comments
Post a Comment