Reputation: 33755
I want to replace all strings that contain the characters c#
which can include c#-4.0
, c#-3.0
, ms-c#
, etc.
How do I check to see if c#
exists within a string, and if it does, just replace the c#
portion of that string?
i.e. for c#-4.0
the modified string would be c%23-4.0
. It would be preferable if a native method of the Ruby core library is used (like one of String
's methods).
I tried tagname.replace('c%23')
but that replaces the entire string, and not just the substring that matches the pattern.
Thoughts?
Upvotes: 2
Views: 1276
Reputation: 54882
You can use the gsub
method of String. (Use sub
if you want to replace only once in the string).
"hello".gsub(/[aeiou]/, '*') #=> "h*ll*"
"hello".gsub(/([aeiou])/, '<\1>') #=> "h<e>ll<o>"
"hello".gsub(/./) {|s| s.ord.to_s + ' '} #=> "104 101 108 108 111 "
"hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}') #=> "h{e}ll{o}"
'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*') #=> "h3ll*"
# in your case :
"some string c#".gsub!('c#', 'c%23') #=> "some string c%23"
Upvotes: 2