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

Use Array.new with a block instead of .times.map. #4658

Closed
tonobo opened this issue Aug 11, 2017 · 1 comment
Closed

Use Array.new with a block instead of .times.map. #4658

tonobo opened this issue Aug 11, 2017 · 1 comment
Assignees

Comments

@tonobo
Copy link

tonobo commented Aug 11, 2017

Expected behavior

To not break application by using auto correct.

Actual behavior

#<ArgumentError: negative array size>

Steps to reproduce the problem

  args.negative_size.times.map do
    puts "test"
  end

rubocop -a

RuboCop version

> rubocop -V
0.49.1 (using Parser 2.4.0.0, running on ruby 2.3.1 x86_64-linux-gnu)
@pocke
Copy link
Collaborator

pocke commented Aug 11, 2017

This is a problem of Performance/TimesMap cop.

Minimal code to reproduce :

-1.times.map{|x| puts x}
$ ruby test.rb # Do nothing

$ rubocop -a --only Performance/TimesMap
Inspecting 1 file
C

Offenses:

test.rb:1:1: C: [Corrected] Use Array.new with a block instead of .times.map.
-1.times.map{|x| puts x}
^^^^^^^^^^^^^^^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense corrected

$ cat test.rb
Array.new(-1){|x| puts x}

$ ruby test.rb
test.rb:1:in `initialize': negative array size (ArgumentError)
	from test.rb:1:in `new'
	from test.rb:1:in `<main>'

@pocke pocke self-assigned this Aug 11, 2017
pocke added a commit to pocke/rubocop that referenced this issue Aug 11, 2017
… by default

See rubocop#4658

This change has three changes.

- Disable auto-correction by default
- Improve the offense message
- Refactoring

Problem
=====

`Integer#times` does nothing if receiver is 0 or less.
However, `Array.new` raises an error if argument is less than 0.

For example:

```ruby
-1.times{}    # does nothing
Array.new(-1) # ArgumentError: negative array size
```

Solution
=====

Disable the non-safe auto-correction by default. And Improve the offense message.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants