Skip to content

Instantly share code, notes, and snippets.

@seniorihor
Created May 30, 2019 14:14
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 seniorihor/8d99d3b4210a211538cdd1e0cb1ac46b to your computer and use it in GitHub Desktop.
Save seniorihor/8d99d3b4210a211538cdd1e0cb1ac46b to your computer and use it in GitHub Desktop.
Cocktail "Recursive": 20% of alcohol, 30% of water and 50% of cocktail "Recursive"...
require "faker" [35/39]
class RecursiveCocktail
def initialize(ingredients: {}, capacity: 500) # default capacity - 500 ml
validate_ingredients!(ingredients)
@ingredients = {}
ingredients.each do |ingredient, percentage|
@ingredients[ingredient] = { percentage: percentage / 100.0, used: 0 }
end
@cocktail_name = generate_cocktail_name
@capacity = capacity
@iteration = 0
end
def mix!
return if cocktail_ready?
run_logger
add_ingredients!
mix!
end
def to_s
<<~COCKTAIL
[ #{current_capacity} ml | #{@iteration} iterations ]
\\ /
|____|
| |
\\ /
||
----
#{@ingredients.map do |ingredient, info|
"#{ingredient}: #{info[:used]} ml"
end.join("\n")}
COCKTAIL
end
private
def run_logger
if @iteration.zero?
print "Preparing cocktail \"#{@cocktail_name}\""
else
print "."
end
@iteration += 1
end
def add_ingredients!
capacity_left = @capacity - current_capacity
@ingredients.each do |_ingredient, info|
info[:used] += (capacity_left * info[:percentage]).ceil
end
end
def current_capacity
@ingredients.map { |_ingredient, info| info[:used] }.inject(:+)
end
def cocktail_ready?
current_capacity >= @capacity
end
def validate_ingredients!(ingredients)
abort "Wrong ingredients list!" if ingredients.empty? || ingredients.size <= 1
percentage =
begin
ingredients.map { |_ingredient, info| info }.inject(:+)
rescue TypeError
0
end
abort "Wrong proportions!" unless (1..100).include?(percentage)
end
def generate_cocktail_name
Faker::Verb.past_participle.capitalize + " " + Faker::Creature::Animal.name.capitalize
end
end
rc = RecursiveCocktail.new(ingredients: { water: rand(1..50), alcohol: rand(1..50) })
rc.mix!
puts rc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment