Escaping single and double quotes in a string in ruby?

前端 未结 9 858
忘了有多久
忘了有多久 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.

提交回复
热议问题