Give a string "5 900 000" i want to get rid of the spaces using gsub with a following pattern: gsub.(/\s/, ''), but that doesn't seem to work. Nor the gsub.(' ', '').
Any ideas guys (ang girls) ?
Give a string "5 900 000" i want to get rid of the spaces using gsub with a following pattern: gsub.(/\s/, ''), but that doesn't seem to work. Nor the gsub.(' ', '').
Any ideas guys (ang girls) ?
>> "5 900 00".gsub(' ','')
=> "590000"
Is it really a string?
.gsub returns the value, if you want to change the variable try .gsub!(" ", "")
If you want to do the replacement in place, you need to use:
str.gsub!(/\s/,'')
Alternatively, gsub returns the string with the replacements
str2 = str.gsub(/\s/,'')
EDIT: Based on your answer, it looks like you have some unprintable characters embedded in the string, not spaces. Using /\D/ as the search string may be what you want. The following will match any non-digit character and replace it with the empty string.
str.gsub!(/\D/,'')
print "5 900 000".gsub(/\s/, '')
Works for me.
Are you affecting the result to the variable ?
"5 900 000".gsub(/\s/,'')
works fine
From what I see you wrote gsub dot (foo,bar) where it must be string.gsub(foo,bar)
The funny thing is that when I print the string i get
697\302\240000
but what gets to the database is: 697 000. I know that patterns i have given should work as well as your suggestions, but this seems to be a little bit 'dodgy' case :-)
Just for kicks: do you even need a regular expression 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!
, the !
method makes the change in place as opposed to returning the changed result. I don't know which you want here.
In a case like this, tr
seems more straightforward to me. I'm not looking for optimization, but it is good to remember that there are lots of string methods other than regular expressions.