123456789_123456789_123456789_123456789_123456789_

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

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, TargetRubyVersion, AutoCorrector, Base
Instance Chain:
self, Base
Inherits: Base
  • Object
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'
+''

Cop Safety Information:

  • This cop’s autocorrection is unsafe because String.new (without operator) is not exactly the same as ''`. These differ in encoding. `String.new.encoding` is always `ASCII-8BIT`. However, `('').encoding is the same as script encoding(e.g. UTF-8). if you expect ASCII-8BIT encoding, disable this cop.

Constant Summary

Instance Method Summary

Instance Method Details

#on_send(node)

[ GitHub ]

  
# 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

#string_value(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/performance/unfreeze_string.rb', line 60

def string_value(node)
  if node.receiver.source == 'String' && node.method?(:new)
    node.arguments.empty? ? "''" : node.first_argument.source
  else
    node.receiver.source
  end
end