Class: RuboCop::Cop::Performance::RedundantMerge

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
Alignment
Defined in:
lib/rubocop/cop/performance/redundant_merge.rb

Overview

Identifies places where ‘Hash#merge!` can be replaced by `Hash#[]=`. You can set the maximum number of key-value pairs to consider an offense with `MaxKeyValuePairs`.

Examples:

# bad
hash.merge!(a: 1)
hash.merge!({'key' => 'value'})

# good
hash[:a] = 1
hash['key'] = 'value'

MaxKeyValuePairs: 2 (default)

# bad
hash.merge!(a: 1, b: 2)

# good
hash[:a] = 1
hash[:b] = 2

Defined Under Namespace

Classes: EachWithObjectInspector

Constant Summary collapse

AREF_ASGN =
'%<receiver>s[%<key>s] = %<value>s'
MSG =
'Use `%<prefer>s` instead of `%<current>s`.'
RESTRICT_ON_SEND =
%i[merge!].freeze
WITH_MODIFIER_CORRECTION =
<<~RUBY
  %<keyword>s %<condition>s
  %<leading_space>s%<indent>s%<body>s
  %<leading_space>send
RUBY

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/rubocop/cop/performance/redundant_merge.rb', line 52

def on_send(node)
  each_redundant_merge(node) do |redundant_merge_node|
    message = message(node)
    add_offense(redundant_merge_node, message: message) do |corrector|
      redundant_merge_candidate(node) do |receiver, pairs|
        new_source = to_assignments(receiver, pairs).join("\n")

        if node.parent && pairs.size > 1
          correct_multiple_elements(corrector, node, node.parent, new_source)
        else
          correct_single_element(corrector, node, new_source)
        end
      end
    end
  end
end