Given a string "5 900 000"
I want to get rid of the spaces using gsub with the following pattern:
gsub(/\s/, '')
but that doesn't seem to work. Nor does:
gsub(' ', '')
Given a string "5 900 000"
I want to get rid of the spaces using gsub with the following pattern:
gsub(/\s/, '')
but that doesn't seem to work. Nor does:
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/,'')
Depending on the situation, you may not need a regular expression. String#tr should work well if you want to replace a single space with the empty string:
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.
tr is a good option? Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made. So if the string doesn't match anything, it will return nil.tr, I think you mean tr!. (The whole difference between tr and tr! is that tr does not make the changes in place. As for returning nil, whether or not that's ok depends on the larger application. The op hasn't given us enough to go on. It might be fine or it might be a mistake.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 :-)