Skip to content

Instantly share code, notes, and snippets.

@arslanfarooq
Created September 25, 2013 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arslanfarooq/1653f172e4192b1e78b9 to your computer and use it in GitHub Desktop.
Save arslanfarooq/1653f172e4192b1e78b9 to your computer and use it in GitHub Desktop.
From "Well Grounded Rubyist" by David A. Black, Listing 5.6: Keeping track of car manufacturing statistics with class variables.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment