Skip to content

Instantly share code, notes, and snippets.

@cadwallion
Created September 30, 2011 00:22
Show Gist options
  • Save cadwallion/1252327 to your computer and use it in GitHub Desktop.
Save cadwallion/1252327 to your computer and use it in GitHub Desktop.
Demon's Music Collection Program
require "csv"
class CD
attr_reader :band_name, :album_name
def initialize(band_name, album_name)
@band_name = band_name
@album_name = album_name
end
def to_string
"#{@band_name}, #{@album_name}"
end
end
class Collection
def initialize
@cds = []
loadFromCSV
end
def loadFromCSV
data = CSV.read('MusicProjectFile.txt', :headers => true)
if data.empty?
CSV.open('MusicProjectFile.txt', 'w') do |csv|
csv << ["Band_Name", "Album_Name"]
end
else
data.each do |row|
cd = CD.new(row['Band_Name'], row['Album_Name'])
addCD(cd)
end
end
end
def addCD(cd)
@cds << cd
writeToCSV
end
def displayCD(indexNum)
@cds[indexNum]
end
def removeCD(indexNum)
@cds.delete_at(indexNum)
writeToCSV
end
def isEmpty?
@cds.length == 0
end
def arrayLength
@cds.length
end
def displayCollection
if !self.isEmpty?
puts "\nYour collection includes:\n"
@cds.each_index do |c|
puts "#{c+1}. #{@cds[c].to_string}"
end
else
puts "\nYour collection is empty."
end
end
def writeToCSV
@cds.sort_by! do |a|
[a.band_name, a.album_name]
end
CSV.open('MusicProjectFile.txt', 'w') do |csv|
csv << ["Band_Name", "Album_Name"]
@cds.each do |cd|
csv << [cd.band_name, cd.album_name]
end
end
end
end
myCollection = Collection.new
quit = false
#Main program loop
while quit == false do
#Main menu
puts "\n\n******MAIN MENU******\n---------------------"
puts "What would you like to do?"
puts "[V]iew my collection"
puts "[A]dd a new CD to my collection"
puts "[R]emove a CD from my collection"
puts "[Q]uit\n---------------------"
prompt1 = gets.chomp.capitalize
# View collection
case prompt1
when 'V', 'VIEW'
myCollection.displayCollection
# Add CD to collection
when 'A', 'ADD'
puts "What is the name of the band? "
tempBandName = gets.chomp
puts "What is the name of the album? "
tempAlbumName = gets.chomp
tempCD = CD.new(tempBandName, tempAlbumName)
myCollection.addCD(tempCD)
puts "\n\"#{tempCD.to_string}\" has been added to your collection."
# Remove CD from collection
when 'R', 'REMOVE'
if !myCollection.isEmpty?
myCollection.displayCollection
puts "Please enter the number corresponding to the band/albuam you'd like to remove."
prompt2 = gets.chomp.to_i
if (1..myCollection.arrayLength) === prompt2
cd = myCollection.displayCD(prompt2 - 1).to_string
myCollection.removeCD(prompt2-1)
puts "\n#{prompt2}. \"#{cd}\" removed."
else
puts "#{prompt2} is not a valid number."
end
else
puts "\n Your collection is empty."
end
# Quit
when 'Q', 'QUIT'
quit = true
else
puts "\nERROR: \"#{prompt1}\" is not a valid entry. Please try again."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment