Class: RuboCop::Cop::Performance::UnfreezeString

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector, TargetRubyVersion
Defined in:
lib/rubocop/cop/performance/unfreeze_string.rb

Overview

In Ruby 2.3 or later, use unary plus operator to unfreeze a string literal instead of ‘String#dup` and `String.new`. Unary plus operator is faster than `String#dup`.

Examples:

# bad
''.dup          # when Ruby 3.2 or lower
"something".dup # when Ruby 3.2 or lower
String.new
String.new('')
String.new('something')

# good
+'something'
+''

Constant Summary collapse

MSG =
'Use unary plus to get an unfrozen string literal.'
RESTRICT_ON_SEND =
%i[dup new].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



47
48
49
50
51
52
53
54
55
56
# File 'lib/rubocop/cop/performance/unfreeze_string.rb', line 47

def on_send(node)
  return unless (dup_string?(node) && target_ruby_version <= 3.2) || string_new?(node)

  add_offense(node) do |corrector|
    string_value = "+#{string_value(node)}"
    string_value = "(#{string_value})" if node.parent&.send_type?

    corrector.replace(node, string_value)
  end
end