Skip to content

Commit 366bbfc

Browse files
committed
Fix Performance/Count cop error on empty selector block
Something like ```ruby collection.reject { }.size ``` would lead to an error
1 parent d080ec3 commit 366bbfc

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#497](https://github.com/rubocop/rubocop-performance/pull/497): Fix `Performance/Count` cop error on empty selector block. ([@viralpraxis][])

lib/rubocop/cop/performance/count.rb

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,16 +117,21 @@ def negate_block_pass_reject(corrector, node)
117117

118118
def negate_block_reject(corrector, node)
119119
target =
120-
if node.receiver.body.begin_type?
120+
if node.receiver.body&.begin_type?
121121
node.receiver.body.children.last
122122
else
123123
node.receiver.body
124124
end
125-
corrector.replace(target, negate_expression(target))
125+
126+
corrector.replace(target || node.receiver.loc.end.adjust(end_pos: -1), negate_expression(target))
126127
end
127128

128129
def negate_expression(node)
129-
"!(#{node.source})"
130+
if node
131+
"!(#{node.source})"
132+
else
133+
'true'
134+
end
130135
end
131136

132137
def negate_block_pass_as_inline_block(node)

spec/rubocop/cop/performance/count_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,4 +353,17 @@ def count(&block)
353353
RUBY
354354
end
355355
end
356+
357+
context 'with `reject` with empty block body' do
358+
it 'registers an offense' do
359+
expect_offense(<<~RUBY)
360+
array.reject {}.size
361+
^^^^^^^^^^^^^^ Use `count` instead of `reject...size`.
362+
RUBY
363+
364+
expect_correction(<<~RUBY)
365+
array.count {true}
366+
RUBY
367+
end
368+
end
356369
end

0 commit comments

Comments
 (0)