Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace "&" to "\&" in Ruby seems impossible?

I want to replace all & characters into \& with String.gsub (or a other method). I've tried several combinations and read another question here, but nothing is gonna work.

  "asdf & asdf".gsub("&", "\\\&") => "asdf & asdf"
like image 234
f00860 Avatar asked Jul 04 '11 09:07

f00860


2 Answers

Your linked question provides a solution - use the block form of gsub:

irb(main):009:0> puts "asdf & asdf".gsub("&"){'\&'}
asdf \& asdf
like image 146
Chowlett Avatar answered Sep 29 '22 06:09

Chowlett


ruby-1.9.2-p180 :008 > puts "asdf & asdf".gsub(/&/, '\\\&')
asdf \& asdf
like image 37
Nicolas Viennot Avatar answered Sep 29 '22 08:09

Nicolas Viennot