#!/usr/bin/ruby
class A
@@a = "a" # a class variable
@b = "a" #a class instance variable
attr_accessor :c
def initialize(c)
@c = c # an instance variable
end
class << self
attr_accessor :b
end
def self.greeting
puts @@a
puts @b
end
end
class B < A
@@a = "b"
@b = "b"
end
A.greeting #=> b a
B.greeting #=> b b
puts A.b
puts A.new('c').c
class变量 当前类及其子类共享
class实例变量 所有实例共享
实例变量 class new出的实例独享
本文通过一个具体的Ruby示例,详细解析了类变量、类实例变量及实例变量的区别与使用方式。介绍了它们的作用域以及如何在类及其子类中共享这些变量。
751

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



