On Sun, Mar 12, 2017 at 9:16 PM, Die Optimisten
<inform / die-optimisten.net> wrote:
> On 2017-03-12 19:12, Mike Stok wrote:
>>>
>>> On Mar 12, 2017, at 2:00 PM, Die Optimisten <inform / die-optimisten.net>
>>> wrote:
>>>
>>> On 2017-03-12 18:16, Mike Stok wrote:
>>>>>
>>>>> On Mar 12, 2017, at 10:09 AM, Die Optimisten
>>>>> <inform / die-optimisten.net> wrote:
>>>>>
>>>>> Hi
>>>>>
>>>>> Is there a nicer way than "\\\\'" for replacing  '  with  \'     ?
>>>>>
>>>>> "ab'cd".gsub(/'/,'\\'+"'")    does interpret \' ...

> Hello!
> ups - I was manacled? hypnotized by / cognitive bound to the very specific
> \\' - behavior
> and didn't realize the block - sorry!
> Thanks for eval,  for now I'll do it that way. - Yes it can be dangerous...

I recommend against using the block form. It incurs unnecessary
overhead and is not needed for this particular use case since the
replacement does not need to be calculated based on the individual
match. If you understand that there are really two levels of escaping
going on (String literals and gsub) the solution is clear immediately:
you need four backslashes to get a literal backslash in the
replacement. Add one backslash for escaping the ' in a single quoted
string and alas:

irb(main):001:0> s="a'b"
=> "a'b"
irb(main):002:0> s.gsub /'/, '\\\\\''
=> "a\\'b"
irb(main):003:0> puts s.gsub /'/, '\\\\\''
a\'b
=> nil

Btw. this has been discussed _numerous_ times on this very list.

Kind regards

robert

-- 
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can
- without end}
http://blog.rubybestpractices.com/

Unsubscribe: <mailto:ruby-talk-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>