一个常量由大写字母开头.它应最多被赋值一次.在ruby的当前版本中,常量的再赋值只会产生警告而不是错误(non-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
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
循序渐进掌握递归正则表达式
一般来说,递归的正则表达式用来匹配任意嵌套层次的结构或左右对称的结构。例如匹配: 递归正则在正则表达式里算是比较灵活的部分,换句话说就是可能会比较难...
[阅读全文]
-
scrapy 使用
启动方式: 写一个启动文件,与配置文件同级 from scrapy.cmdline import execute import sys,os sys...
[阅读全文]
-
-
-
经典例题
例题: 1.用户输入账号 2.用户输入密码 3.判断用户的账号是不是alex 4.如果账号是alex在继续判断密码是不是alexdsb 5.账号和密...
[阅读全文]
-
-
-
-
-
网友评论