I'm assigning an array constant like this:
NUMS = *(2..9)
Rubocop says
C: Freeze mutable objects assigned to constants.
NUMS = *(2..9)
^^^^^
So I try
NUMS = *(2..9).freeze
Rubocop says
C: Freeze mutable objects assigned to constants.
NUMS = *(2..9).freeze
^^^^^^^^^^^^
Tried
NUMS = (*(2..9)).freeze
Rubocop says
E: unexpected token tRPAREN
(Using Ruby 2.0 parser; configure using TargetRubyVersion parameter, under AllCops)
NUMS = (*(2..9)).freeze
^
Tried
NUMS = [1, 2, 3, 4, 5, 6, 7, 8, 9].freeze
Rubocop says
== happy_robot_dance (no errors)
I say
My hand hurts from typing 1, 2, 3, ... 9
Is there some way to use the splat to assign and freeze a constant?
Solutions
NUMS = (2..9).to_a.freeze
NUMS = Array(2..9).freeze
This case was previously unaccounted for by RuboCop (read bug.)
I have added an issue and a pull request that will fix this.
Meanwhile you can silence the cop by disabling it for this case using:
# rubocop:disable Style/MutableConstant
NUMS = *(2..9)
# rubocop:enable Style/MutableConstant
Or you can use #to_a
:
NUMS = (2..9).to_a.freeze
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With