I don't see immediate answers to this in the ML but others might still
have answered it already.

On Fri, Aug 31, 2012 at 5:50 PM, Luke Pearce <[email protected]> wrote:
> Using 1.9.3p194:
>
>> puts "\+"
> +
>
>> puts "\\+"
> \+
>
>> puts "\\"
> \
>
> However not what I'd expect (1):
>
>> puts "hi + bye".gsub(/\+/, "\\+")
> hi  bye
>
> This gives the expected output:
>
>> puts "hi + bye".gsub(/\+/, "\\\\+")
> hi \+ bye
>
> I can understand why I need to double escape the + to get \+ in the
> output but shouldn't (1) above at least print "hi + bye"?

There are two levels of escapes and it happens that the backslash is
the escape character for _both levels_:

1. string (i.e. what makes "\n" create a string with the line terminator)
2. regular expression replacement pattern (e.g. \1 as a backreference)

If you want to have a literal backslash in the result, you need to
escape it, i.e. you need this in the replacement string
\\

To get that, you need to escape each backslash so string escaping does
not eat it, so you do

"\\\\"

irb(main):005:0> puts "\\"
\
=> nil
irb(main):006:0> puts "\\\\"
\\
=> nil

Kind regards

robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- You received this message because you are subscribed to the Google Groups 
ruby-talk-google group. To post to this group, send email to 
[email protected]. To unsubscribe from this group, send email 
to [email protected]. For more options, visit this 
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en

Reply via email to