Class: RuboCop::StringInterpreter

Inherits:
Object
  • Object
show all
Defined in:
lib/rubocop/string_interpreter.rb

Overview

Take a string with embedded escapes, and convert the escapes as the Ruby interpreter would when reading a double-quoted string literal. For example, ā€œ\nā€ will be converted to ā€œnā€.

Constant Summary collapse

STRING_ESCAPES =
{
  '\a' => "\a", '\b' => "\b", '\e' => "\e", '\f' => "\f", '\n' => "\n",
  '\r' => "\r", '\s' => ' ',  '\t' => "\t", '\v' => "\v", "\\\n" => ''
}.freeze
STRING_ESCAPE_REGEX =
/\\(?:
  [abefnrstv\n]     |   # simple escapes (above)
  \d{1,3}           |   # octal byte escape
  x[0-9a-fA-F]{1,2} |   # hex byte escape
  u[0-9a-fA-F]{4}   |   # unicode char escape
  u\{[^}]*\}        |   # extended unicode escape
  .                     # any other escaped char
)/x

Class Method Summary collapse

Class Method Details

.interpret(string) ⇒ Object



22
23
24
25
26
27
# File 'lib/rubocop/string_interpreter.rb', line 22

def interpret(string)
  # We currently don't handle \cx, \C-x, and \M-x
  string.gsub(STRING_ESCAPE_REGEX) do |escape|
    STRING_ESCAPES[escape] || interpret_string_escape(escape)
  end
end