Strip / replace spaces within a string

For line "5 900 000"

I want to get rid of spaces using gsub with the following pattern:

 gsub(/\s/, '') 

but this does not seem to work. Doesn't:

 gsub(' ', '') 
+6
ruby regex
source share
9 answers

If you want to make a replacement in place, you need to use:

 str.gsub!(/\s/,'') 

In addition, gsub returns a replacement string

 str2 = str.gsub(/\s/,'') 

EDIT . Based on your answer, it looks like you have some non-printable characters embedded in a string, not spaces. Using / \ D / as the search string may be what you want. The following will match any asymmetric character and replace it with an empty string.

 str.gsub!(/\D/,'') 
+22
source share
 >> "5 900 00".gsub(' ','') => "590000" 

Is this really a string?

.gsub returns if you want to change the try.gsub variable! ("," ")

+7
source share

Just for kicks: do you even need a regex here? String#tr should do the trick just fine:

 telemachus ~ $ irb >> "500 500 12".tr(' ', '') => "50050012" >> "500 500 12".tr!(' ', '') => "50050012" 

As with gsub and gsub! method ! makes a replacement instead of returning a modified result. I do not know what you want here.

In this case, tr seems to me more understandable. I'm not looking for optimization, but it's good to remember that there are many string methods other than regular expressions.

+4
source share

I suggest making str.gsub!(/\s+/, '') for efficiency reasons.

+2
source share

Try this hope, it will help:

 2.2.1 :001> str= " Jai Kumar rajput "; # " Jai Kumar rajput " 2.2.1 :001> str.squish.downcase.tr(" ",""); # "JaiKumarRajput" 
+2
source share

"5 900 000".gsub(/\s/,'') works "5 900 000".gsub(/\s/,'') fine

From what I see, you wrote gsub dot (foo, bar) where it should be string.gsub (foo, bar)

+1
source share
 print "5 900 000".gsub(/\s/, '') 

It works for me.

Do you influence the result on the variable?

0
source share

do you mean

 str.gsub!.(/\s/,'') 

with an exclamation mark?

0
source share

The funny thing is that when I print a line, I get

697 \ 302 \ 240000

but what gets into the database: 697,000. I know that the templates I gave should work just like your suggestions, but this seems to be a bit of a “quirky” case :-)

0
source share

All Articles