Skip to content

Instantly share code, notes, and snippets.

@jordanpoulton
Created March 4, 2013 17:59
Show Gist options
  • Save jordanpoulton/5084134 to your computer and use it in GitHub Desktop.
Save jordanpoulton/5084134 to your computer and use it in GitHub Desktop.
Practise 2 from Well Grounded Rubyist
class Car
#CLASS LEVEL VARIABLES AND METHODS
@@makes = []
@@cars = {}
def self.total_count #ATTRIBUTE READER
@total_count ||= 0
end
def self.total_count=(n) #ATTRIBUTE WRITER
@total_count = n
end
def self.show_makes # ATTRIBUTE READER FOR MAKES
return @@makes
end
def self.add_make(make) #ADD MAKE TO @@MAKES
unless @@makes.include?(make) #CHECK MAKE DOES NOT EXIST
@@makes << make #APPENDS ARGUMENT make TO @@MAKES
@@cars[make] = 0 # INITIALISES KEY make => value 0 to @@CARS
puts "Added make #{make}" #CONFIRMS MAKE ADDED
end
end
#INSTANCE OBJECT LEVEL VARIABLE AND METHODS
attr_reader :make
def initialize(make)
if @@makes.include?(make)
puts "Creating new make #{make}!"
@make = make
@@cars[make] +=1
self.class.total_count +=1 #writes TO LINE 11
else
puts "No such make #{make}."
end
end
def make_mates
@@cars[self.make]
end
end
c = Car.new("First make")
puts Car.total_count
Car.add_make("Nissan")
Car.add_make("VOLVO")
d = Car.new("Nissan")
#e = Car.new("Volvo")
puts Car.total_count
puts d.make
puts Car.show_makes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment