Ruby rubocop: how to freeze an array constant generated with splat

末鹿安然 提交于 2019-12-23 12:55:41

问题


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

回答1:


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



回答2:


I think this is a case of appeasing Rubocop for its own sake - case 2 looks like it should work and therefore could be considered a bug. However, does this work?

why_do_i_exist = *(2..9)
NUMS = why_do_i_exist.freeze



回答3:


You can try:

NUMS = Array[*2..9].freeze



来源:https://stackoverflow.com/questions/38757237/ruby-rubocop-how-to-freeze-an-array-constant-generated-with-splat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!