find and replace percent symbol within string with back slash in ruby?

683 views Asked by At

I tried this :

irb(main):125:0> a = "ab%c"
=> "ab%c"
irb(main):126:0> a.gsub("%", '\\')
=> "ab\\c"
irb(main):127:0>

whereas expected output is:

ab\c

it did not work.

Thanks in advance.

Update: ruby version

ruby -v
ruby 1.8.7 (2011-06-30 patchlevel 352) [x86_64-linux]
1

There are 1 answers

0
shivam On BEST ANSWER
a = "ab%c"
a.gsub!("%", '\\')  
#=> "ab\\c"
puts a
# ab\c 

in "ab\\c" backslash \ is being escaped using character \. you can verify this with puts