Skip to content

Style/MapCompactWithConditionalBlock replaces with #reject when it should be #select #12683

Closed
@danbee

Description

Rubocop replaces the following code:

new_items = items.map do |item|
  next unless meets_certain_condition?(item)
  item
end.compact

with:

new_items = items.reject { |item| meets_certain_condition?(item) }

This looks reasonable at first glance, but actually flips the conditional and returns the inverse set of results to the set we really want. The correct code should be:

new_items = items.select { |item| meets_certain_condition?(item) }

I've created an example project that illustrates the problem at https://github.com/danbee/rubocop_test/tree/main


Expected behavior

I expect Rubocop to replace the code with code that has equivalent functionality.

Actual behavior

The conditional for what gets returns gets flipped.

Steps to reproduce the problem

Create a Ruby file with the above code and try formatting it with the Style/MapCompactWithConditionalBlock rule.

RuboCop version

$ rubocop -V
1.60.2 (using Parser 3.3.0.5, rubocop-ast 1.30.0, running on ruby 2.7.8) [arm64-darwin23]

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions