Skip to content

Instantly share code, notes, and snippets.

@amy-mac
Created September 29, 2013 01:04
Show Gist options
  • Save amy-mac/ebaf2e60f0c185e809ce to your computer and use it in GitHub Desktop.
Save amy-mac/ebaf2e60f0c185e809ce to your computer and use it in GitHub Desktop.
Gluten Free lab project for WDI - Week One
#Title: Gluten Free
#Prerequisites:
#- Ruby
# - Exceptions
# - Hashes & Arrays
# - Objects & Classes
#Objectives:
#- Work with exceptions, classes, class variables, conditions
# ======================================================================
# Create a Person class. A person will have a stomach and allergies
# Create a method that allows the person to eat and add arrays of food to their stomachs
# If a food array contains a known allergy reject the food.
class AllergyError < StandardError
end
class Person
attr_accessor :stomach, :allergies
def initialize(allergies)
@allergies = allergies
@stomach = []
end
def allergy_test
@stomach.each do |food|
if food == @allergies
@stomach = []
raise AllergyError
end
end
end
def eat(foods)
@stomach << foods
@stomach.flatten!
puts "You now have #{@stomach.join(', ')} in your stomach."
allergy_test
rescue AllergyError
puts "Uh oh, you've eaten #{@allergies} and threw up."
end
end
# Create a Person named Chris. Chris is allergic to gluten.
# Create a Person named Beth. Beth is allergic to scallops.
# Feed them the following foods
pizza = ["cheese", "gluten", "tomatoes"]
pan_seared_scallops = ["scallops", "lemons", "pasta", "olive oil"]
water = ["h", "h", "o"]
chris = Person.new('gluten')
beth = Person.new('scallops')
chris.eat(pizza)
chris.eat(water)
chris.eat(pan_seared_scallops)
beth.eat(pizza)
beth.eat(water)
beth.eat(pan_seared_scallops)
# When a person attempts to eat a food they are allergic to, raise a custom exception
# For example: AllergyError
# Bonus: When a person attempts to eat a food they are allergic to,
# ... remove ALL the food from the person's stomach before raising the exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment