class RuboCop::StringInterpreter

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ā€.

Constants

STRING_ESCAPES
STRING_ESCAPE_REGEX

Public Class Methods

interpret(string) click to toggle source
# File lib/rubocop/string_interpreter.rb, line 21
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

Private Class Methods

interpret_hex(escape) click to toggle source
# File lib/rubocop/string_interpreter.rb, line 48
def interpret_hex(escape)
  [escape[2..-1].hex].pack('C'.freeze)
end
interpret_octal(escape) click to toggle source
# File lib/rubocop/string_interpreter.rb, line 52
def interpret_octal(escape)
  [escape[1..-1].to_i(8)].pack('C'.freeze)
end
interpret_string_escape(escape) click to toggle source
# File lib/rubocop/string_interpreter.rb, line 30
def interpret_string_escape(escape)
  case escape[1]
  when 'u'.freeze then interpret_unicode(escape)
  when 'x'.freeze then interpret_hex(escape)
  when /\d/       then interpret_octal(escape)
  else
    escape[1] # literal escaped char, like \\
  end
end
interpret_unicode(escape) click to toggle source
# File lib/rubocop/string_interpreter.rb, line 40
def interpret_unicode(escape)
  if escape[2] == '{'.freeze
    escape[3..-1].split(/\s+/).map(&:hex).pack('U*'.freeze)
  else
    [escape[2..-1].hex].pack('U'.freeze)
  end
end