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 = 1, 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