Reputation:
I have this String
s = "03:23 PM on 09/04/12"
I want to take out the ' on ' and replace it with just a space ' '. I thought the string's gsub method, along with regex, would be the best solution. I am just not sure why this wont work.
s ="03:23 PM on 09/04/12"
s.gsub(/ on /, ' ')
puts s
#=> "03:23 PM on 09/04/12"
Upvotes: 0
Views: 280
Reputation: 126722
A string's gsub
method returns the modified string and leaves the object string alone. If you want to modify the object in-place then you have to use gsub!
.
Also, if you want to change only one occurrence then sub
is probably your best bet.
So
s = "03:23 PM on 09/04/12"
s = s.sub(' on ', ' ')
or
s.sub!(' on', ' ')
Upvotes: 3
Reputation: 118261
s ="03:23 PM on 09/04/12"
s.gsub(' on ', ' ')
#>> "03:23 PM 09/04/12"
You can go without regex
in this case,but if you want to use regex
,then use s.gsub!(/ on /, ' ')
Upvotes: 0
Reputation: 29032
You are not required to use a Regexp object for the gsub parameter (/ on /
) you can also use a string - this worked for me!
s = "03:23 PM on 09/04/12"
p s.gsub " on ", " "
#=> "03:23 PM 09/04/12"
Upvotes: 2
Reputation: 78413
works fine for me... Perhaps you meant to use gsub!
?
>> s ="03:23 PM on 09/04/12"
=> "03:23 PM on 09/04/12"
>> s.gsub(/ on /, ' ')
=> "03:23 PM 09/04/12"
>> s.gsub!(/ on /, ' ')
=> "03:23 PM 09/04/12"
>> s
=> "03:23 PM 09/04/12"
Upvotes: 2