<分区>
Possible Duplicate:
What does @@variable mean in Ruby?
用双'@'声明一个对象有什么区别
@@lexicon = Lexicon.new()
并在 Ruby 中使用单个“@”声明对象?
@lexicon = Lexicon.new()
<分区>
Possible Duplicate:
What does @@variable mean in Ruby?
用双'@'声明一个对象有什么区别
@@lexicon = Lexicon.new()
并在 Ruby 中使用单个“@”声明对象?
@lexicon = Lexicon.new()
最佳答案
不同的是,第一个是类变量,第二个是实例变量。
实例变量仅可用于对象的那个实例。即
class Yasin
def foo=(value)
@foo = value
end
def foo
@foo
end
end
yasin = Yasin.new
yasin.foo=1
yasin.foo #=> 1
yasin_2 = Yasin.new
yasin_2.foo #> nil
类变量可用于定义类变量的类(和子类,iirc)的所有实例。
class Yasin
def foo=(value)
@@foo = value
end
def foo
@@foo
end
end
yasin = Yasin.new
yasin.foo=1
yasin.foo #=> 1
yasin_2 = Yasin.new
yasin_2.foo #=> 1
关于ruby - 在 Ruby 中用单 '@' 和双 '@' 声明对象的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13248510/