class RuboCop::Cop::Lint::RedundantStringCoercion

Checks for string conversion in string interpolation, ‘print`, `puts`, and `warn` arguments, which is redundant.

@example

# bad
"result is #{something.to_s}"
print something.to_s
puts something.to_s
warn something.to_s

# good
"result is #{something}"
print something
puts something
warn something

Constants

MSG_DEFAULT
MSG_SELF
RESTRICT_ON_SEND

Public Instance Methods

on_interpolation(begin_node) click to toggle source
# File lib/rubocop/cop/lint/redundant_string_coercion.rb, line 34
def on_interpolation(begin_node)
  final_node = begin_node.children.last

  return unless to_s_without_args?(final_node)

  register_offense(final_node, 'interpolation')
end
on_send(node) click to toggle source
# File lib/rubocop/cop/lint/redundant_string_coercion.rb, line 42
def on_send(node)
  return if node.receiver

  node.each_child_node(:send) do |child|
    next if !child.method?(:to_s) || child.arguments.any?

    register_offense(child, "`#{node.method_name}`")
  end
end

Private Instance Methods

register_offense(node, context) click to toggle source
# File lib/rubocop/cop/lint/redundant_string_coercion.rb, line 54
def register_offense(node, context)
  receiver = node.receiver
  template = receiver ? MSG_DEFAULT : MSG_SELF
  message = format(template, context: context)

  add_offense(node.loc.selector, message: message) do |corrector|
    replacement = receiver ? receiver.source : 'self'

    corrector.replace(node, replacement)
  end
end