为什么到处都是冻结常数? [英] Why are there frozen constants everywhere?
问题描述
我们可以从许多著名的存储库中轻松找到此类样式,例如机架、导轨等.
We can easily find such style from lots of famous repositories, like rack, rails, etc.
PATH_INFO = 'PATH_INFO'.freeze
REQUEST_METHOD = 'REQUEST_METHOD'.freeze
SCRIPT_NAME = 'SCRIPT_NAME'.freeze
QUERY_STRING = 'QUERY_STRING'.freeze
CACHE_CONTROL = 'Cache-Control'.freeze
CONTENT_LENGTH = 'Content-Length'.freeze
CONTENT_TYPE = 'Content-Type'.freeze
HTTP_IF_MODIFIED_SINCE = 'HTTP_IF_MODIFIED_SINCE'.freeze
HTTP_IF_NONE_MATCH = 'HTTP_IF_NONE_MATCH'.freeze
HTTP_IF_NONE_MATCH = 'HTTP_IF_NONE_MATCH'.freeze
我想知道为什么这些常量字符串会被冻结.既然都是常量,应该只有一个实例.当然我们可以把 "foo".freeze
放在某个地方来引用同一个单例实例,但是人们通常会写像 HTTP_IF_MODIFIED_SINCE
这样的字面变量名.
I wonder why these constant strings are frozen. Since they are all constants, there should be only one instance. Of course we can put "foo".freeze
somewhere to reference the same singleton instance, however people usually write literal variable name like HTTP_IF_MODIFIED_SINCE
instead.
所以在我看来,尽管使用 #freeze
并没有任何区别,那么人们为什么要冻结常量?
So in my opinion, it doesn't make any difference in spite of using #freeze
, so why do people freeze constants?
推荐答案
当您为已经初始化的常量重新赋值时,Ruby 会打印警告是正确的:
It is correct that Ruby prints a warning when you re-assign a value to an already initialized constant:
> FOO = 'foo'
> FOO = 'bar'
# :2: warning: already initialized constant FOO
# :1: warning: previous definition of FOO was here
> FOO
# => "bar"
但是没有保护可以改变常量中的值.没有 freeze
的例子:
But there is no protection from changing the value in the constant. Example without freeze
:
> FOO = 'foo'
> FOO[1] = '-'
> FOO
# => "f-o"
但是 freeze
允许保护常量的值不被更改.freeze
示例:
But freeze
allows to protect the value of the constants from being changed. Example with freeze
:
> FOO = 'foo'.freeze
> FOO[1] = '-'
# => RuntimeError: can't modify frozen String
这篇关于为什么到处都是冻结常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!