Last active
April 1, 2020 03:55
-
-
Save harrisonmalone/1cd82490d8392e6ee00e20170d8b7766 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Allergy | |
attr_reader :score | |
@@allergies = { | |
eggs: 1, | |
peanuts: 2, | |
shellfish: 4, | |
strawberries: 8, | |
tomatoes: 16, | |
chocolate: 32, | |
pollen: 64, | |
cats: 128 | |
}.to_a.reverse.to_h | |
def initialize(name, score) | |
validate(score) | |
@name = name.capitalize | |
@score = score | |
@list = get_allergies | |
end | |
def validate(score) | |
if score > 255 || score < 1 | |
raise StandardError, "Wrong score. Enter a number between 1 and 255" | |
end | |
end | |
def get_allergies | |
allergic_to = [] | |
temp = @score | |
@@allergies.each do |key, value| | |
if temp >= value | |
allergic_to << key | |
temp -= value | |
end | |
end | |
return allergic_to | |
end | |
def list_print_pretty | |
items = @list.map.with_index do |item, index| | |
if index == @list.length - 1 | |
" and #{item}" | |
elsif index == @list.length - 2 | |
item | |
else | |
"#{item}, " | |
end | |
end | |
return items.join("") | |
end | |
def list | |
"#{@name} is allergic to #{list_print_pretty}" | |
end | |
def allergic_to_item?(item) | |
@list.include?(item.to_sym) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require_relative 'allergy' | |
tom = Allergy.new("tom", 255) | |
p tom.allergic_to_item?("chocolate") | |
p tom.list | |
p tom.score |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment