| 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
本文通过一个Ruby类的实例详细解释了不同类型的变量及其作用范围,包括全局变量、实例变量、局部变量、常量和类变量,并展示了这些变量如何在实际代码中被使用。
62

被折叠的 条评论
为什么被折叠?



