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