Inserting Escape Characters

后端 未结 2 455
轻奢々
轻奢々 2021-01-23 22:40

I want to replace and insert escape character sequences with their escape character values, also taking into account that \'\\\' nullifies the escape character.

For exam

2条回答
  •  深忆病人
    2021-01-23 22:53

    I assume you are reffering to the following problem:

    "\\n".gsub(/\\\\/, "\\").gsub(/\\n/, "\n") # => "n"
    "\\n".gsub(/\\n/, "\n").gsub(/\\\\/, "\\") # => "\\\n"
    

    String#gsub can take a block argument, which performs the substitution.

    str.gsub(/\\(.)/) do |s|
      case $1
      when "n"
        "\n"
      when "t"
        "\t"
      else
        $1
      end
    end
    

    This way no special escape sequence is substituted first and everything works as expeted.

提交回复
热议问题