Skip to content

Commit

Permalink
[Fix rubocop#11104] Fix an error for Style/CollectionCompact
Browse files Browse the repository at this point in the history
Fixes rubocop#11104.

This PR fixes an error for `Style/CollectionCompact`
when using `reject` method and receiver is a variable.
  • Loading branch information
koic committed Oct 22, 2022
1 parent f3a101c commit a34f43e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_an_error_for_style_collection_compact.md
@@ -0,0 +1 @@
* [#11104](https://github.com/rubocop/rubocop/issues/11104): Fix an error for `Style/CollectionCompact` when using `reject` method and receiver is a variable. ([@koic][])
4 changes: 3 additions & 1 deletion lib/rubocop/cop/style/collection_compact.rb
Expand Up @@ -96,7 +96,9 @@ def offense_range(node)
end

def to_enum_method?(node)
TO_ENUM_METHODS.include?(node.children.first.method_name)
return false unless node.receiver.send_type?

TO_ENUM_METHODS.include?(node.receiver.method_name)
end

def good_method_name(node)
Expand Down
15 changes: 15 additions & 0 deletions spec/rubocop/cop/style/collection_compact_spec.rb
Expand Up @@ -57,6 +57,21 @@
RUBY
end

it 'registers an offense and corrects when using `reject` and receiver is a variable' do
expect_offense(<<~RUBY)
def foo(params)
params.reject { |_k, v| v.nil? }
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `compact` instead of `reject { |_k, v| v.nil? }`.
end
RUBY

expect_correction(<<~RUBY)
def foo(params)
params.compact
end
RUBY
end

it 'does not register an offense when using `reject` to not to rejecting nils' do
expect_no_offenses(<<~RUBY)
array.reject { |e| e.odd? }
Expand Down

0 comments on commit a34f43e

Please sign in to comment.