Replacing ' with \'

Discussion in 'Ruby' started by Nikita Petrov, Sep 12, 2008.

  1. In my practice I need to replace apostrophe with backslash and
    apostrophe in string. I using String#gsub, but it has unpredictable
    result in my own. That's I do in IRB to test my gsub call:

    irb(main):001:0> str = "O'Reilly"
    => "O'Reilly"
    irb(main):002:0> str.gsub("'", "\\'")
    => "OReillyReilly"

    As You see I have magic result: I want to have "O\\'Reilly", but result
    is one - "OReillyReilly".

    Does anybody known how to fix this problem? Thanks.
     
    Nikita Petrov, Sep 12, 2008
    #1
    1. Advertisements

  2. Nikita Petrov

    Thomas B. Guest

    The backslash has a special meaning in gsub. Use str.gsub("'", "\\\\'")
    instead.

    TPR.
     
    Thomas B., Sep 12, 2008
    #2
    1. Advertisements

  3. Thanks, that helped me.
     
    Nikita Petrov, Sep 12, 2008
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.