Rubocop: Spurious useless assignment warning on reduce

Created on 28 Apr 2014  路  5Comments  路  Source: rubocop-hq/rubocop

$ rubocop -V
0.21.0 (using Parser 2.1.9, running on ruby 2.0.0 x86_64-linux-gnu)

The following code example produces the warning below. Of course in this case the assignment isn't useless as sum is carried on to the next call of the block.

x = [1, 4, 9].reduce(0) do |sum, n|
  sum += Math.sqrt n
end
puts x
Inspecting 1 file
W

Offenses:

/tmp/x.rb:2:3: W: Useless assignment to variable - sum. Use just operator +.
  sum += Math.sqrt n
  ^^^

1 file inspected, 1 offense detected

Most helpful comment

@yujinakayama Actually - don't. This is not a bug, of course.

@michaelmior The assignment is redundant indeed. This is functionally the same:

x = [1, 4, 9].reduce(0) do |sum, n|
  sum + Math.sqrt(n)
end

You don't actually need to modify sum, your only concern is the return value of the block.

All 5 comments

@yujinakayama, please have a look at this.

@yujinakayama Actually - don't. This is not a bug, of course.

@michaelmior The assignment is redundant indeed. This is functionally the same:

x = [1, 4, 9].reduce(0) do |sum, n|
  sum + Math.sqrt(n)
end

You don't actually need to modify sum, your only concern is the return value of the block.

Ack, you're right. Sorry about that. Clearly I didn't take the time to think this through. I thought something seemed fishy. Thanks!

Well, at least this issue has one use: explaining this error to people who are encountering it themselves, and also thought it was a bug at first.

I also thought this was a bug, and I wasted a chunk of time troubleshooting it. The error message was very unclear to me.

I believe this might be very easily fixed by saying something like 'use just operator + instead of +='.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

millisami picture millisami  路  3Comments

lepieru picture lepieru  路  3Comments

mlammers picture mlammers  路  3Comments

Aqualon picture Aqualon  路  3Comments

NobodysNightmare picture NobodysNightmare  路  3Comments