Name Begins With | Variable Scope |
---|---|
$ | A global variable |
@ | An instance variable |
[a-z] or _ | A local variable |
[A-Z] | A constant |
@@ | A class variable |
以一个简单例子示例各种变量的区别:
class Female# ConstantSEX = 'female'# Class variable: shared among all instances of this class@@sex = SEXdef initialize( weight, height)# Instance variable: accessible to specific instance of this class@weight = weight@height = heightenddef self.sex@@sexenddef description# Local variable: local to this blockideal_weight = @height * 0.8puts 'This female ideal weight would be ' + ideal_weight.to_s + ' and her actually weight is ' + @weight.to_sendendputs Female.new(130, 170).description
puts Female.sex