慕慕森
类上的实例变量:class Parent @things = [] def self.things @things end def things self.class.things endendclass Child < Parent @things = []endParent.things << :carChild.things << :dollmom = Parent.newdad = Parent.newp Parent.things #=> [:car]p Child.things #=> [:doll]p mom.things #=> [:car]p dad.things #=> [:car]类变量:class Parent @@things = [] def self.things @@things end def things @@things endendclass Child < ParentendParent.things << :carChild.things << :dollp Parent.things #=> [:car,:doll]p Child.things #=> [:car,:doll]mom = Parent.newdad = Parent.newson1 = Child.newson2 = Child.newdaughter = Child.new[ mom, dad, son1, son2, daughter ].each{ |person| p person.things }#=> [:car, :doll]#=> [:car, :doll]#=> [:car, :doll]#=> [:car, :doll]#=> [:car, :doll]使用类上的实例变量(不在该类的实例上),您可以存储该类的公共内容,而不会自动获取子类(反之亦然)。使用类变量,您可以方便地不必self.class从实例对象写入,并且(在需要时)您还可以在整个类层次结构中自动共享。将这些合并到一个示例中,该示例还包含实例上的实例变量:class Parent @@family_things = [] # Shared between class and subclasses @shared_things = [] # Specific to this class def self.family_things @@family_things end def self.shared_things @shared_things end attr_accessor :my_things def initialize @my_things = [] # Just for me end def family_things self.class.family_things end def shared_things self.class.shared_things endendclass Child < Parent @shared_things = []end然后在行动:mama = Parent.newpapa = Parent.newjoey = Child.newsuzy = Child.newParent.family_things << :housepapa.family_things << :vacuummama.shared_things << :carpapa.shared_things << :blenderpapa.my_things << :quadcopterjoey.my_things << :bikesuzy.my_things << :dolljoey.shared_things << :puzzlesuzy.shared_things << :blocksp Parent.family_things #=> [:house, :vacuum]p Child.family_things #=> [:house, :vacuum]p papa.family_things #=> [:house, :vacuum]p mama.family_things #=> [:house, :vacuum]p joey.family_things #=> [:house, :vacuum]p suzy.family_things #=> [:house, :vacuum]p Parent.shared_things #=> [:car, :blender]p papa.shared_things #=> [:car, :blender]p mama.shared_things #=> [:car, :blender]p Child.shared_things #=> [:puzzle, :blocks] p joey.shared_things #=> [:puzzle, :blocks]p suzy.shared_things #=> [:puzzle, :blocks]p papa.my_things #=> [:quadcopter]p mama.my_things #=> []p joey.my_things #=> [:bike]p suzy.my_things #=> [:doll]