如果我有下面这段Ruby代码:
class Blah
def self.bleh
@blih = "Hello"
@@bloh = "World"
end
end@blih和@@bloh到底是什么?@blih是Blah类中的一个实例变量,而@@bloh是Blah类中的一个类变量,对吗?这是否意味着@@bloh是Blah的class类中的一个变量?
发布于 2010-04-08 19:38:00
人们似乎忽略了这个方法是一个类方法。
@blih将是常量Bleh的class实例的实例变量。因此:
irb(main):001:0> class Bleh
irb(main):002:1> def self.bleh
irb(main):003:2> @blih = "Hello"
irb(main):004:2> @@blah = "World"
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> Bleh.instance_variables
=> []
irb(main):008:0> Bleh.bleh
=> "World"
irb(main):009:0> Bleh.instance_variables
=> ["@blih"]
irb(main):010:0> Bleh.instance_variable_get :@blih
=> "Hello"@@blah将作为Bleh的类变量提供:
irb(main):017:0> Bleh.class_variables
=> ["@@blah"]
irb(main):018:0> Bleh.send :class_variable_get, :@@blah
=> "World"发布于 2010-04-08 19:25:05
这种疯狂是有办法的..。
class Example
@foo # class instance variable
@@bar # class variable
def fun1
@baz # instance variable
end
end实例变量
实例变量(示例中的@foo和@baz )始终以@开头,并且它们始终属于,无论对象本身引用:要么是类的对象,要么是表示类的类对象。类定义或类方法中的实例变量引用与实例方法中的实例变量引用完全不同。
继承
因为实例变量不是由类定义的,所以它们与继承机制无关,-they只是在为它们赋值时创建的。类实例变量是表示类的class对象的简单实例变量,因此不会被继承。
类变量
类变量对于类方法和类的实例方法以及类定义本身都是可见的,并由类方法和实例方法共享。类变量可以在实例方法、类方法中使用,也可以在任何方法之外的类定义本身中使用。类变量总是根据封闭的类定义语句创建的类对象进行计算。
类实例变量与实例变量
类实例变量的一个缺点是它们不能像类变量那样在实例方法中使用。另一个缺点是可能会将它们与普通实例变量混淆。与类变量相比,类实例变量的优势在于在对现有类进行子类化时类变量的混乱行为:如果类使用类变量,则任何子类都可以通过更改共享类变量的值来更改类及其所有后代的行为。这是使用类实例变量而不是类变量的有力论据。
其中很大一部分来自优秀的"The Ruby Programming Language"

发布于 2010-04-08 17:41:37
以两个at符号为前缀的变量是类变量,可在类的实例和类方法中访问。
示例:
class CountEm
@@children = 0
def initialize
@@children += 1
@myNumber = @@children
end
def whoAmI
"I'm child number #@myNumber (out of #@@children)"
end
def CountEm.totalChildren
@@children
end
end
c1 = CountEm.new
c2 = CountEm.new
c3 = CountEm.new
c1.whoAmI # -> "I'm child number 1 (out of 3)"
c3.whoAmI # -> "I'm child number 3 (out of 3)"
CountEm.totalChildren # -> 3取自link text的示例
https://stackoverflow.com/questions/2598794
复制相似问题