Ruby Rubocop:如何冻结由Splat生成的数组常量 [英] Ruby rubocop: how to freeze an array constant generated with splat

查看:153
本文介绍了Ruby Rubocop:如何冻结由Splat生成的数组常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在分配一个这样的数组常量:

I'm assigning an array constant like this:

NUMS = *(2..9)

Rubocop说

C:冻结分配给常量的可变对象.
NUMS = *(2..9)
;   ^^^^^

C: Freeze mutable objects assigned to constants.
NUMS = *(2..9)
               ^^^^^

所以我尝试

NUMS = *(2..9).freeze

Rubocop说

C:冻结分配给常量的可变对象.
NUMS = *(2..9).freeze
;    ^^^^^^^^^^^^^

C: Freeze mutable objects assigned to constants.
NUMS = *(2..9).freeze
               ^^^^^^^^^^^^

尝试

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

Rubocop说

E:意外令牌tRPAREN (使用Ruby 2.0解析器;在AllCops下使用TargetRubyVersion参数进行配置)
NUMS =(*(2..9)).freeze
;        ^

E: unexpected token tRPAREN (Using Ruby 2.0 parser; configure using TargetRubyVersion parameter, under AllCops)
NUMS = (*(2..9)).freeze
                         ^

尝试

NUMS = [1, 2, 3, 4, 5, 6, 7, 8, 9].freeze

Rubocop说

== happy_robot_dance(无错误)

== happy_robot_dance (no errors)

我说

输入1、2、3,... 9会伤手

My hand hurts from typing 1, 2, 3, ... 9

是否可以使用splat分配和冻结常量?

Is there some way to use the splat to assign and freeze a constant?

解决方案

NUMS = (2..9).to_a.freeze

NUMS = Array(2..9).freeze

推荐答案

RuboCop以前没有说明这种情况(阅读错误.)

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

或者您可以使用#to_a:

NUMS = (2..9).to_a.freeze

这篇关于Ruby Rubocop:如何冻结由Splat生成的数组常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆