diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index f404c1fa8ed5..2445bf304ca3 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -13,7 +13,7 @@ InternalAffairs/NodeDestructuring: # Offense count: 50 # Configuration parameters: CountComments. Metrics/ClassLength: - Max: 186 + Max: 187 # Offense count: 209 # Configuration parameters: CountComments, ExcludedMethods. diff --git a/lib/rubocop/ast/node/array_node.rb b/lib/rubocop/ast/node/array_node.rb index 8731440e75f4..f8f2f44b46f4 100644 --- a/lib/rubocop/ast/node/array_node.rb +++ b/lib/rubocop/ast/node/array_node.rb @@ -18,6 +18,19 @@ def values each_child_node.to_a end + # Calls the given block for all values in the `array` literal. + # + # @yieldparam [Node] node each node + # @return [self] if a block is given + # @return [Enumerator] if no block is given + def each_value(&block) + return to_enum(__method__) unless block_given? + + values.each(&block) + + self + end + # Checks whether the `array` literal is delimited by square brackets. # # @return [Boolean] whether the array is enclosed in square brackets diff --git a/lib/rubocop/config_loader.rb b/lib/rubocop/config_loader.rb index b1f15c287309..e9b23ffb2495 100644 --- a/lib/rubocop/config_loader.rb +++ b/lib/rubocop/config_loader.rb @@ -55,7 +55,10 @@ def load_file(file) end def add_missing_namespaces(path, hash) - hash.keys.each do |key| + # Using `hash.each_key` will cause the + # `can't add a new key into hash during iteration` error + hash_keys = hash.keys + hash_keys.each do |key| q = Cop::Cop.qualified_cop_name(key, path) next if q == key diff --git a/lib/rubocop/cop/lint/percent_string_array.rb b/lib/rubocop/cop/lint/percent_string_array.rb index 4e55ffd72bdf..d7cc903b1821 100644 --- a/lib/rubocop/cop/lint/percent_string_array.rb +++ b/lib/rubocop/cop/lint/percent_string_array.rb @@ -42,7 +42,7 @@ def on_percent_literal(node) def autocorrect(node) lambda do |corrector| - node.values.each do |value| + node.each_value do |value| range = value.loc.expression match = range.source.match(TRAILING_QUOTE) diff --git a/spec/rubocop/ast/array_node_spec.rb b/spec/rubocop/ast/array_node_spec.rb index a582bb61f893..128462cbf821 100644 --- a/spec/rubocop/ast/array_node_spec.rb +++ b/spec/rubocop/ast/array_node_spec.rb @@ -31,6 +31,24 @@ end end + describe '#each_value' do + let(:source) { '[1, 2, 3]' } + + context 'with block' do + it { expect(array_node.each_value {}.is_a?(described_class)).to be(true) } + it do + ret = [] + array_node.each_value { |i| ret << i.to_s } + + expect(ret).to eq(['(int 1)', '(int 2)', '(int 3)']) + end + end + + context 'without block' do + it { expect(array_node.each_value.is_a?(Enumerator)).to be(true) } + end + end + describe '#square_brackets?' do context 'with square brackets' do let(:source) { '[1, 2, 3]' }