Escaping single and double quotes in a string in ruby?

前端 未结 9 799
忘了有多久
忘了有多久 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 10:00

    One caveat:

    Using %Q[] and %q[] for string comparisons is not intuitively safe.

    For example, if you load something meant to signify something empty, like "" or '', you need to use the actual escape sequences. For example, let's say qvar equals "" instead of any empty string.

    This will evaluate to false
    if qvar == "%Q[]"

    As will this,
    if qvar == %Q[]

    While this will evaluate to true
    if qvar == "\"\""

    I ran into this issue when sending command-line vars from a different stack to my ruby script. Only Gabriel Augusto's answer worked for me.

    0 讨论(0)
  • 2020-12-05 10:02

    You can use Q strings which allow you to use any delimiter you like:

    str = %Q|ruby 'on rails" " = ruby 'on rails|
    
    0 讨论(0)
  • 2020-12-05 10:06

    Use backslash to escape characters

    str = "ruby \'on rails\" "
    
    0 讨论(0)
提交回复
热议问题