class Rubocop::Cop::Style::CharacterLiteral

Checks for uses of the character literal ?x.

Constants

MSG

Public Instance Methods

autocorrect_action(node) click to toggle source
# File lib/rubocop/cop/style/character_literal.rb, line 25
def autocorrect_action(node)
  string = node.loc.expression.source[1..-1]

  if string.length == 1 # normal character
    replace(node.loc.expression, "'#{string}'")
  elsif string.length == 2 # special character like \n
    replace(node.loc.expression, %Q("#{string}"))
  end
end
on_str(node) click to toggle source
# File lib/rubocop/cop/style/character_literal.rb, line 10
def on_str(node)
  # Constants like __FILE__ are handled as strings,
  # but don't respond to begin.
  return unless node.loc.respond_to?(:begin)

  # we don't register an offence for things like ?\C-\M-d
  if node.loc.begin.is?('?') && node.loc.expression.source.size < 4
    add_offence(:convention, node.loc.expression, MSG)
    do_autocorrect(node)
  end
end