rubocop offense but not sure what is wrong

550 views Asked by At

I am cleaning up some code that I've inherited and there's this line but to be honest, I'm not sure what rubocop is trying to tell me is wrong with it.

  total_cost = tmp_totals.inject { |total, tmp_val| total + tmp_val }

I am getting this error

app/models/item_count.rb:58:40: C: Name inject block params |acc, elem|

that looks like this:

enter image description here

I am just trying to get past this cop. Any ideas what it is telling me to fix?

2

There are 2 answers

1
infused On BEST ANSWER

By default Rubocop wants you to name those two variables acc and elem instead of total and tmp_val. You can configure the variables it wants in your own rubycop.yml. The defaults are setup like this:

Style/SingleLineBlockParams:
  Methods:
    - reduce:
        - acc
        - elem
    - inject:
        - acc
        - elem
1
Eric Duminil On

Rubocop is a bit too rigid with this one. It should just check that the second parameter isn't called mem or acc IMHO. Just use :

total_cost = tmp_totals.inject(0) { |acc, elem| acc + elem }

Or

total_cost = tmp_totals.inject(0, :+)

Rubocop won't complain, and you'll get 0 instead of nil for an empty array.

If you're not sure what rubocop complains about, you could :

  • make sure your code is committed

  • use rubocop -a script.rb

  • check if the code still works

  • check what the difference is