【发布时间】:2013-11-26 08:12:03
【问题描述】:
@ - 实例变量 @@ - 类变量。
因此,如果没有创建实例,则不应共享实例变量值。但是:
class Add
def self.add(what)
if not defined? @a
@a = 0
end
@a += what
puts @a.to_s
end
end
Add.add(4)
Add.add(4)
结果:
$ruby main.rb
4
8
为什么?
【问题讨论】:
-
旁白:
@a ||= 0是if not defined? @a...的常用替代品。前者是@a = @a || 0的简写,就像x += 1是x = x + 1一样。
标签: ruby variables instance-variables class-variables