Ruby学习札记(1)-常量

Ruby学习札记(1)-常量

 

Ruby中有一种传说“约定优于配置”,因此Ruby的语法有特别约定,而且Ruby是弱类型的语言,所以语法和JavaC/C++C#等很不一样。对于初学者,只好慢慢习惯了L

 

Ruby常量以大写字母开头,一般建议全部大写。常量只能在类、模块里定义,而不能在方法中定义。

 

Learn By Example

Example 1:类中和类外使用常量

class Person Constant = 2; puts "The constant is " + Constant.to_s end puts Person::Constant

Example 2:常量在继承关系中

class First INFO = "Ruby"; end class Second INFO = "Hello"; class FirstChild < First puts INFO; puts First::INFO end end

结果如下:

Hello

Ruby

Example 3:常量可以再次赋值(会出现警告)

class First INFO = "Raby"; INFO = "Ruby"; end puts First::INFO

结果如下:

D:/workruby/MegaGreeter/example.rb:12: warning: already initialized constant INFO

Ruby

你可能感兴趣的:(java,C#,Class,Ruby,语言)