A constant starts with an uppercase letter. it should be assigned a maximum of once. in the current Ruby version, a constant value assignment only generates warnings rather than errors (non-ANSI eval. RB will not report this warning)
Ruby> fluid = 30
30
Ruby> fluid = 31
31
Ruby> Solid = 32
32
Ruby> Solid = 33
(Eval): 1: Warning: already initialized constant solid
33
Constants can be defined in the class, but unlike real variables, they can be accessed outside the class.
Ruby> class constclass
| C1 = 1, 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
Constants can also be defined in the module.
Ruby> module constmodule
| C1 = 101
| C2 = 102
| C3 = 103
| def showconstants
| print C1, "", C2, "", C3, "\ n"
| 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