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
# Constant
SEX = 'female'
# Class variable: shared among all instances of this class
@@sex = SEX
def initialize( weight, height)
# Instance variable: accessible to specific instance of this class
@weight = weight
@height = height
end
def self.sex
@@sex
end
def description
# Local variable: local to this block
ideal_weight = @height * 0.8
puts 'This female ideal weight would be ' + ideal_weight.to_s + ' and her actually weight is ' + @weight.to_s
end
end
puts Female.new(130, 170).description
puts Female.sex