【问题标题】:Stop Ruby from Automatically Escaping Strings阻止 Ruby 自动转义字符串
【发布时间】:2013-10-06 23:23:55
【问题描述】:

如果我有字符串 "this is a \#test" 并将其放入 Python shell,我会返回 'this is a \\#test',这就是我正在寻找的行为。但是,如果我将它放入 Ruby shell 中,我会返回 "this is a #test",但没有任何迹象表明存在反斜杠。如何使 Ruby 字符串表现得像 Python,即不自动转义我的 # 符号?

【问题讨论】:

    标签: ruby escaping


    【解决方案1】:

    当您不想解释转义序列时使用单引号。

    [1] pry(main)> 'this is a \#test'
    => "this is a \\#test"
    

    单引号也不会做字符串插值,所以如果你需要both,你可以手动转义你的斜线:

    [1] pry(main)> t = "test" ; "this is a \\##{t}"
    => "this is a \\#test"
    

    【讨论】:

    • 单引号是gets 方法的默认行为吗?
    • gets 方法不会执行任何插值或转义序列。它与引用没有任何关系——它只是从标准输入中读取字符。
    • @Kvass:Get 永远不会转义字符。
    • 如果字符串存储在某个文件中怎么办?
    【解决方案2】:

    只用单引号代替双引号:

    'this is a \#test'
    

    将包含反斜杠。在 Ruby 中,只有 " 字符串会进行替换和转义。 ' 字符串只转义 \\\

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多