Lex W. wrote:
I understand the first \ , as it will produce \ when it’s displayed ,
but why are there still 2 more \ ? As I see it , \\’ would produce
\’ , and only when it will be printed will we see ’ . Could someone
please explain this ?
Inside a single- or double-quoted string, \ is an escape character, and
to get a literal backslash you have to escape it with another backslash.
So “\” is a single backslash; “\\” is two backslashes.
irb(main):002:0> “\”.size
=> 1
Inside a regexp replacement string, backslash is also an escape
character, because (for example) \1 means “substitute the first capture
group”, i.e. the string inside the first set of parentheses.
irb(main):006:0> “abc123def”.gsub(/(\d+)/, ‘\1’)
=> “abc123def”
So to actually substitute a backslash, the replacement string has to
contain backslash backslash, and you need to write that as “\\” or
‘\\’
irb(main):007:0> “abc123def”.gsub(/\d+/, ‘\\’)
=> “abc\def”
^
this is a single backslash in the replacement
If using the block form of gsub then there is no need for the \1 syntax,
since there are other ways of achieving the same thing, and so the
second level of backslash escaping is disabled.
irb(main):009:0> “abc123def”.gsub(/(\d+)/) { “#{$1}” }
=> “abc123def”
irb(main):010:0> “abc123def”.gsub(/\d+/) { ‘\’ }
=> “abc\def”
Of course, if all this is for escaping SQL, whatever DB access library
you use likely has existing methods to do this for you. e.g. for
ActiveRecord:
n = “o’reilly”
Person.find(:all, :conditions => [“name=?”, n])
HTH,
Brian.