Skip to content

Commit

Permalink
Fix a false positive for Style/CollectionCompact
Browse files Browse the repository at this point in the history
This PR fixes a false positive for `Style/CollectionCompact` when using `reject`
on hash to reject nils in Ruby 2.3 analysis.
Because `Hash#compact` and `Hash#compact!` have been introduced in Ruby 2.4.
  • Loading branch information
koic committed Apr 14, 2023
1 parent 8dfe1b4 commit c626673
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11799](https://github.com/rubocop/rubocop/pull/11799): Fix a false positive for `Style/CollectionCompact` when using `reject` on hash to reject nils in Ruby 2.3 analysis. ([@koic][])
3 changes: 3 additions & 0 deletions lib/rubocop/cop/style/collection_compact.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,14 @@ module Style
class CollectionCompact < Base
include RangeHelp
extend AutoCorrector
extend TargetRubyVersion

MSG = 'Use `%<good>s` instead of `%<bad>s`.'
RESTRICT_ON_SEND = %i[reject reject! select select!].freeze
TO_ENUM_METHODS = %i[to_enum lazy].freeze

minimum_target_ruby_version 2.4

# @!method reject_method_with_block_pass?(node)
def_node_matcher :reject_method_with_block_pass?, <<~PATTERN
(send !nil? {:reject :reject!}
Expand Down
11 changes: 10 additions & 1 deletion spec/rubocop/cop/style/collection_compact_spec.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# frozen_string_literal: true

RSpec.describe RuboCop::Cop::Style::CollectionCompact, :config do
RSpec.describe RuboCop::Cop::Style::CollectionCompact, :config, :ruby24 do
it 'registers an offense and corrects when using `reject` on array to reject nils' do
expect_offense(<<~RUBY)
array.reject { |e| e.nil? }
Expand Down Expand Up @@ -157,4 +157,13 @@ def foo(params)
RUBY
end
end

context 'when Ruby <= 2.3', :ruby23 do
it 'does not register an offense when using `reject` on hash to reject nils' do
expect_no_offenses(<<~RUBY)
hash.reject { |k, v| v.nil? }
hash.reject! { |k, v| v.nil? }
RUBY
end
end
end

0 comments on commit c626673

Please sign in to comment.