编辑代码

class Car
    ## @@makes是一个数组,用于存储厂家的信息
    ## @@cars是一个散列:一个索引控制的结构,索引是汽车厂家名,对应值是每个厂家拥有汽车数量
    ## @@total_count是一个用于统计所有创建的汽车数量的计数器
    @@makes = [] # 类变量
    @@cars = {} # 类变量
    attr_reader :make

    def self.total_count # 类方法
        @total_count ||= 0 # 实例变量
    end

    def self.total_count=(n)
        @total_count = n
    end

    def self.add_make(make)
        unless @@makes.include?(make)
            @@makes << make
            @@cars[make] = 0
        end
    end

    def initialize(make)
        if @@makes.include?(make)
            puts "Creating a new #{make}!"
            @make = make
            @@cars[make] += 1
            self.class.total_count += 1
            # 这里的self是实例,self.class是Car这个类对象
            # self.class.total_count相当于类方法total_count=(n)
        else
            raise "No such make: #{make}."
        end
    end
    
    def make_mates  # 实例方法
        @@cars[self.make]
    end
end

# 注册汽车品牌
Car.add_make("Honda")
Car.add_make("Ford")

# 生产汽车
h = Car.new("Honda")
f = Car.new("Ford")
h2 = Car.new("Honda")

# h2所属厂家一共造了多少量 Car
puts "Counting cars of same make as h2..."
puts "There are #{h2.make_mates}"

# 所有汽车
puts "Counting total cars..."
puts "There are #{Car.total_count}"

class Hybrid < Car
end

h3 = Hybrid.new("Honda")
f2 = Hybrid.new("Ford")
# h2所属厂家一共造了多少量 Hybrid
puts "There are #{Hybrid.total_count} hybrids on the road!"