Escaping single and double quotes in a string in ruby?

前端 未结 9 798
忘了有多久
忘了有多久 2020-12-05 09:33

How can I escape single and double quotes in a string?

I want to escape single and double quotes together. I know how to pass them separately but don\'t know how to

相关标签:
9条回答
  • 2020-12-05 09:41

    My preferred way is to not worry about escaping and instead use %q, which behaves like a single-quote string (no interpolation or character escaping), or %Q for double quoted string behavior:

    str = %q[ruby 'on rails" ] # like single-quoting
    str2 = %Q[quoting with #{str}] # like double-quoting: will insert variable
    

    See https://docs.ruby-lang.org/en/trunk/syntax/literals_rdoc.html#label-Strings and search for % strings.

    0 讨论(0)
  • 2020-12-05 09:42

    I would use just: str = %(ruby 'on rails ") Because just % stands for double quotes(or %Q) and allows interpolation of variables on the string.

    0 讨论(0)
  • 2020-12-05 09:44

    Here is an example of how to use %Q[] in a more complex scenario:

      %Q[
        <meta property="og:title" content="#{@title}" />
        <meta property="og:description" content="#{@fullname}'s profile. #{@fullname}'s location, ranking, outcomes, and more." />
      ].html_safe
    
    0 讨论(0)
  • 2020-12-05 09:48

    I would go with a heredoc if I'm starting to have to worry about escaping. It will take care of it for you:

    string = <<MARKER 
    I don't have to "worry" about escaping!!'"!!
    MARKER
    

    MARKER delineates the start/end of the string. start string on the next line after opening the heredoc, then end the string by using the delineator again on it's own line.

    This does all the escaping needed and converts to a double quoted string:

    string
    => "I don't have to \"worry\" about escaping!!'\"!!\n"
    
    0 讨论(0)
  • 2020-12-05 09:53
    >> str = "ruby 'on rails\" \" = ruby 'on rails"
    => "ruby 'on rails" " = ruby 'on rails"
    
    0 讨论(0)
  • 2020-12-05 09:56

    Here is a complete list:

    From http://learnrubythehardway.org/book/ex10.html

    0 讨论(0)
提交回复
热议问题