在Ruby中重新分配常量时抛出异常? [英] Throw exception when re-assigning a constant in Ruby?

查看:144
本文介绍了在Ruby中重新分配常量时抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我早就知道Ruby中的常量(即,大写的变量名称)不是 常量。像其他编程语言一样,对对象的引用是存储在变量/常量中的唯一的东西。 (Sidebar:Ruby确实有冻结被引用对象被修改的功能,据我所知,这不是许多其他语言提供的功能。)



所以这里是我的问题:当你将一个值重新分配给一个常量时,你会收到如下警告:

 > ;> FOO ='bar'
=> bar
>> FOO ='baz'
(irb):2:warning:已初始化常数FOO
=> baz

有没有办法强制Ruby抛出异常而不是打印警告?很难找出为什么有时会发生重新分配。

解决方案

查看这个问题,看看在某些情况下如何将警告视为错误是可能的。



否则我猜你必须编写一个自定义方法来分配常量,并在已经分配的情况下引发异常。



如果您知道特定常量发生重新分配,您还可以在作业之前添加一个理智支票。


I've long been aware that "constants" in Ruby (i.e., variable names that are capitalized) aren't really constant. Like other programming languages, a reference to an object is the only thing stored in the variable/constant. (Sidebar: Ruby does have the facility to "freeze" referenced objects from being modified, which as far as I know, isn't an ability offered in many other languages.)

So here's my question: when you re-assign a value into a constant, you get a warning like so:

>> FOO = 'bar'
=> "bar"
>> FOO = 'baz'
(irb):2: warning: already initialized constant FOO
=> "baz"

Is there a way to force Ruby to throw an exception instead of printing a warning? It's tough to figure out why reassignments happen sometimes.

解决方案

Look at this question to see how it is possible in some cases to treat warnings as errors.

Otherwise I guess you'd have to write a custom method to assign constants and raise the exception if already assigned.

If you know that a reassignment happens to a specific constant, you can also add a sanity check just before the assignment.

这篇关于在Ruby中重新分配常量时抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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