class RuboCop::Cop::Performance::UnfreezeString
+”
+‘something’
# good
String.new(‘something’)
String.new(”)
String.new
“something”.dup # when Ruby 3.2 or lower
”.dup # when Ruby 3.2 or lower
# bad
@example
if you expect ‘ASCII-8BIT` encoding, disable this cop.
`ASCII-8BIT`. However, `(+”).encoding` is the same as script encoding(e.g. `UTF-8`).
exactly the same as `+”`. These differ in encoding. `String.new.encoding` is always
This cop’s autocorrection is unsafe because ‘String.new` (without operator) is not
@safety
Unary plus operator is faster than `String#dup`.
literal instead of `String#dup` and `String.new`.
In Ruby 2.3 or later, use unary plus operator to unfreeze a string
def on_send(node)
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
def string_value(node)
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