Ruby 常量的基本定义与赋值规则
常量必须以大写字母作为起始字符,其设计初衷是仅允许被赋值一次。在 Ruby 的当前版本实现中,如果尝试对已定义的常量进行重新赋值,解释器只会发出警告信息而不会抛出错误(注:非 ANSI 标准的 eval.rb 版本可能不会报告此警告)。
ruby>fluid=30
30
ruby>fluid=31
31
ruby>Solid=32
32
ruby>Solid=33
(eval):1: warning: already initialized constant Solid
33
常量不仅可以定义在类内部,而且与实例变量不同,它们支持从类的外部进行访问。
ruby> class ConstClass
| C1=101
| C2=102
| C3=103
| def show
| print C1," ",C2," ",C3,"\n"
| end
| end
nil
ruby> C1
ERR: (eval):1: uninitialized constant C1
ruby> ConstClass::C1
101
ruby> ConstClass.new.show
101 102 103
nil
除了类之外,常量也可以定义在模块中。
ruby> module ConstModule
| C1=101
| C2=102
| C3=103
| def showConstants
| print C1," ",C2," ",C3,"\n"
| end
| end
nil
ruby> C1
ERR: (eval):1: uninitialized constant C1
ruby> include ConstModule
Object
ruby> C1
101
ruby> showConstants
101 102 103
nil
ruby> C1=99 # not really a good idea
99
ruby> C1
99
ruby> ConstModule::C1 # the module's constant is undisturbed ...
101
ruby> ConstModule::C1=99
ERR: (eval):1: compile error
(eval):1: parse error
ConstModule::C1=99
^
ruby> ConstModule::C1 # .. regardless of how we tamper with it.
101