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
|
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
.
Constant Summary
-
MSG =
# File 'lib/rubocop/cop/performance/unfreeze_string.rb', line 33'Use unary plus to get an unfrozen string literal.'
-
RESTRICT_ON_SEND =
# File 'lib/rubocop/cop/performance/unfreeze_string.rb', line 34%i[dup new].freeze
Instance Method Summary
- #on_send(node)
- #string_value(node) private
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