红宝石常数是什么意思? [英] What does Ruby constant mean?
问题描述
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?
推荐答案
没错,constants 就像 ruby 中的 variables,但是如果你改变了你会得到一个警告他们.
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
您可以通过 Constants::PI
访问 PI
,而 Constants::other
将不起作用.
You can reach PI
doing Constants::PI
while Constants::other
will not work.
这篇关于红宝石常数是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!