secret
Created

From "Well Grounded Rubyist" by David A. Black, Listing 5.6: Keeping track of car manufacturing statistics with class variables.

  • Download Gist
5.6_class_variables.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
puts "\n"
# --> Keeping track of car manufacturing statistics with class variables <--
 
class Car
@@makes = [] #1
@@cars = {}
@@total_count = 0
attr_reader :make #2
def self.total_count #3
@@total_count
end
 
def self.cars #3
@@cars
end
def self.add_make(make) #4
unless @@makes.include?(make)
@@makes << make
@@cars[make] = 50 # ?????
end
end
def initialize(make)
if @@makes.include?(make)
puts "Creating a new #{make}!"
@make = make #5
@@cars[make] += 1 #6
@@total_count += 1
else
raise "No such make: #{make}." #7
end
end
def make_mates #8
@@cars[self.make]
end
end
 
#1
# defining class variables:
# @@make is an array.
# @@cars is a hash, whose keys are makes of cars, and the corresponding
# values to the keys are counts of how many of each make there are.
# @@total_count is how many cars have been created.
 
#2
# reader attribute 'make' enables us to ask each car what its make is.
# value of 'make' is set when a car is created.
# and there's no writer attribute because we don't want code outside the
# class changing the make of cars that already exist.
 
#3
# to provide access to @@total_count, we define the total_count method.
 
Car.add_make("Honda")
Car.add_make("Toyota")
Car.add_make("Nissan")
 
h1 = Car.new("Honda")
h2 = Car.new("Honda")
t1 = Car.new("Toyota")
t2 = Car.new("Toyota")
t3 = Car.new("Toyota")
 
puts "\nTotal Toyotas are: "
p t3.make_mates
#t2 = Car.new("Ford")
 
puts "\nTotal cars are: #{Car.total_count}"
puts "@@cars: "
p Car.cars

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.