问题描述
Ruby常数真正意味着什么?以下代码未显示任何常量属性。警告在那里,但我仍然可以更改A的含义。
What does Ruby constants really mean? The following code doesn't show any 'constant' attribute. The warning is there, but I still get to change what A refers to.
A = 1
puts A # => 1
A = 2 # warning: already initialized constant A
puts A # => 2
还是Ruby常数只是没有任何强制性的指示?
Or is Ruby constants are just an indication without any enforcement?
推荐答案
是的,常量就像红宝石中的变量一样,但是如果您进行更改,则会收到警告
That's right, constants are just like variables in ruby, but you get a warning if you change them.
此外,纯变量也有一个区别:即使常量是在另一个类或模块中定义的,也可以访问常量,例如给出以下代码段:
Also, there's one difference with mere variables: You can access constants even if they are defined inside another class or module, for example given this snippet:
module Constants
PI = 3,1415
other = "variable"
end
您可以通过常量来达到
,而 PI
:: PI Constants :: other
不起作用。
You can reach PI
doing Constants::PI
while Constants::other
will not work.
这篇关于Ruby常数是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!