本文已参与「新人创作礼」活动,一起开启掘金创作之路。
一、Ruby支持的变量
Ruby支持五种类型的变量
- 变量(局部变量)
- 全局变量
- 实例变量
- 类变量
- 常数
Ⅰ、变量 Variable
普通变量也是局部变量,以小写、下划线开头,在方法中被定义、在方法中被使用,与大部分语言的变量是相同定义。
def show
a = 1
puts "a is #{a}"
end
show
a is 1
使用
#{expr}格式化输出变量
Ⅱ、全局变量 Global variable
全局变量以$符号开头,能够跨类、跨方法调用
$glob = 1
def show
puts "$glob is #$glob"
end
class Test1
def show
puts "$glob is #{$glob}"
end
end
class Test2
def show
puts "$glob is #{$glob}"
end
end
show
t1 = Test1.new
t1.show
t2 = Test2.new
t2.show
$glob is 1
$glob is 1
$glob is 1
字符串格式化输出全局变量时,在双引号内使用#$xxx,当然#{$xxx}也可以
Ⅲ、实例变量 Instance variable
实例变量以@开头,对同一个实例、对象中所有方法共享,与this.xxx相同,不再赘述
class T
def initialize(a)
@a = a
end
def show
puts "@a is #@a"
end
end
t = T.new
t.show
@a is 1
字符串格式化输出实例变量时,在双引号内使用#@xxx即可
Ⅳ、类变量 Class variable
类变量以@@开头,类似private,它是同一个类所有实例共享的变量,不同实例都可以调用
class T
@@a = 1
def show
puts "@@a is #@@a"
end
def add
@@a += 1
end
end
t1 = T.new
t2 = T.new
t2.show
t1.add
t2.show
@@a is 1
@@a is 2
字符串格式化输出类变量时,在双引号内使用
#@@xxx即可
Ⅴ、常数 Constant
常数以大写字母开头,为了区分,通常全大写,注意,常数不能在类方法中定义
VAR = 1
二、伪变量
比较类似于:C的内置宏、PHP常量等,是一些内置变量
- self:当前方法的接收器对象
- true
- false
- nil:undefined,未定义变量的默认值
- __FILE__:当前文件名
- __LINE__:当前行号