Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cop idea: prefer to_set {...} over map {...}.to_set #11339

Closed
vlad-pisanov opened this issue Dec 27, 2022 · 1 comment · Fixed by #11340
Closed

Cop idea: prefer to_set {...} over map {...}.to_set #11339

vlad-pisanov opened this issue Dec 27, 2022 · 1 comment · Fixed by #11340

Comments

@vlad-pisanov
Copy link

vlad-pisanov commented Dec 27, 2022

This new cop would be a twin of Style/MapToHash, but for .to_set:

# bad
list.map { |x| x + 1 }.to_set
list.collect(&:to_s).to_set
# good
list.to_set { |x| x + 1 }
list.to_set(&:to_s)

Performance-wise, both ways appear to be identical (although there may be some additional memory benefit in avoiding the intermediate .map since sets are implemented using hashes internally 🤷‍♂️)

koic added a commit to koic/rubocop that referenced this issue Dec 27, 2022
Fixes rubocop#11339.

This PR adds new `Style/MapToSet` cop

This cop looks for uses of `map.to_set` or `collect.to_set` that could be
written with just `to_set`. It is unsafe, as it can produce false positives
if the receiver is not an `Enumerable`.

```ruby
# bad
something.map { |i| i * 2 }.to_set

# good
something.to_set { |i| i * 2 }

# bad
[1, 2, 3].collect { |i| i.to_s }.to_set

# good
[1, 2, 3].to_set { |i| i.to_s }
```
@koic koic mentioned this issue Dec 27, 2022
8 tasks
@koic
Copy link
Member

koic commented Dec 27, 2022

This idea looks good to me. I've opened #11340.

bbatsov pushed a commit that referenced this issue Dec 28, 2022
Fixes #11339.

This PR adds new `Style/MapToSet` cop

This cop looks for uses of `map.to_set` or `collect.to_set` that could be
written with just `to_set`. It is unsafe, as it can produce false positives
if the receiver is not an `Enumerable`.

```ruby
# bad
something.map { |i| i * 2 }.to_set

# good
something.to_set { |i| i * 2 }

# bad
[1, 2, 3].collect { |i| i.to_s }.to_set

# good
[1, 2, 3].to_set { |i| i.to_s }
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants