当前位置: 移动技术网 > IT编程>脚本编程>Ruby > ruby 类常量 解析

ruby 类常量 解析

2017年12月12日  | 移动技术网IT编程  | 我要评论
 一个常量由大写字母开头.它应最多被赋值一次.在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   

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网