Skip to content

Instantly share code, notes, and snippets.

@benjaminjb
Last active August 29, 2015 14:05
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 benjaminjb/0ef05665c1f4500f57c9 to your computer and use it in GitHub Desktop.
Save benjaminjb/0ef05665c1f4500f57c9 to your computer and use it in GitHub Desktop.
first day hw--a recipe parser
class Recipe
attr_reader :name, :servings, :ingredients
def initialize(name, servings)
@name = name
@servings = servings
@ingredients = []
end
def add_ingredient(i)
@ingredients << i
end
# I added this publish method just to see if it was working correctly/make it look nice
def publish
print "For #{@name}, you will need:\n"
print ( @ingredients.map {|ingred| "#{ingred.quantity} #{ingred.units} #{ingred.name}"}.join("\n"))
print "\nServes #{@servings}.\n"
end
end
class Ingredient
attr_reader :name, :quantity, :units
def initialize(name, quantity=:to_taste, units=nil)
@name = name
@quantity = quantity
@units = units
end
end
class RecipeParser
def self.parse
cookbook = []
raw = File.read('recipes.txt')
step1 = raw.split("\n\n")
step2 = step1.map { |x| x.split("\n") }
step3 = step2.map do |rec|
{
name: rec.first,
serves: rec[1].split.last.to_i,
ingredients: rec[2..-1]
}
end
step3.map do |rec|
temp = Recipe.new(rec[:name],rec[:serves])
rec[:ingredients].each {|ing| temp.add_ingredient(self.ingredient_parse(ing))}
cookbook << temp
end
self.display(cookbook)
end
def self.ingredient_parse(line)
ingredient_line = line.split
measure_units = ["oz","tbs","lbs","cup"]
counter = 0
if ingredient_line.first.to_i > 0
quantity = ingredient_line.first.to_i
counter += 1
if measure_units.include?(ingredient_line[1])
units = ingredient_line[1]
counter += 1
end
end
name = ingredient_line[counter..-1].join(" ")
return Ingredient.new(name,quantity,units)
end
# Again, I added this display method just to help me see the results.
def self.display(cookbook)
cookbook.each { |recipe| recipe.publish }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment