diff --git a/lib/rubocop/cop/style/hash_as_last_array_item.rb b/lib/rubocop/cop/style/hash_as_last_array_item.rb index f2abbd9005c..43ca432af7f 100644 --- a/lib/rubocop/cop/style/hash_as_last_array_item.rb +++ b/lib/rubocop/cop/style/hash_as_last_array_item.rb @@ -1,5 +1,4 @@ # frozen_string_literal: true -require 'byebug' module RuboCop module Cop @@ -76,8 +75,8 @@ def check_no_braces(node) return if node.children.empty? # Empty hash cannot be "unbraced" add_offense(node, message: 'Omit the braces around the hash.') do |corrector| + remove_last_element_trailing_comma(corrector, node.parent) corrector.remove(node.loc.begin) - remove_last_element_trailing_comma(corrector, node) corrector.remove(node.loc.end) end end @@ -91,7 +90,7 @@ def remove_last_element_trailing_comma(corrector, node) range: node.children.last.source_range, side: :right ).end.resize(1) - + corrector.remove(range) if range.source == ',' end end diff --git a/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb b/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb index d05251ea10a..50518a661b1 100644 --- a/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb +++ b/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb @@ -61,7 +61,7 @@ RUBY expect_correction(<<~RUBY) - [1, 2, one: 1, two: 2 ,] + [1, 2, one: 1, two: 2, ] RUBY end @@ -82,8 +82,23 @@ [ 1, 2, - one: 1, - two: 2, + #{' '} + one: 1, + two: 2, + #{' '} + ] + RUBY + end + + it 'does not register an offense when hash is not the last element' do + expect_no_offenses(<<~RUBY) + [ + 1, + 2, + { + one: 1 + }, + two: 2 ] RUBY end