Challenge 8: Pizza Party

Challenge number 8 is all about pizza! I might be a bit hungry while I’m writing this, hence the enthusiasm. The problem statement for number 8 is to write a program to evenly divide pizzas based on number of people, number of pizzas, and number of slices per pizza. It also asks that the program return the number of leftover slices, if any.

This is relatively easy to begin with, and is a logical progression from challenge 6, with number validation. That’s where I started: include the getInteger(prompt) method to ensure numbers instead of words. Ruby division defaults to rounding down, and the mod method (%) returns the remainder. This is handy for figuring out the leftovers. The working code for this challenge consists of two lines, and it looks like this:

slices_per_person = number_of_pizzas * slices_per_pizza / number_of_people

leftovers = number_of_pizzas * slices_per_pizza % number_of_people

The interesting part of this challenge has to do with an extra challenge: how to make sure the text has agreement between quantity of things, and the noun for those things. I was planning on writing my own method to determine whether a word should be plural, but then it turned out there’s a gem that already does that for you!

By adding the line require ‘active_support/inflector’, I was able to make the output from the program have the correct conjugation by using the .pluralize() method, which helpfully takes a number as an argument. Unhelpfully, .pluralize() doesn’t change some words, such as “is” and “are”. I used a shorthand ternary operator in that case: 

"There #{leftovers == 1? 'is' : 'are'} #{leftovers} leftover #{"piece".pluralize(leftovers)}"

Here are the results: 

That was a relatively easy one for today! Check out my github repo if you want to see how all the code looks together!

Published by corbettbw

I am a Ruby developer in Phoenix, AZ. I'm interested in the intersection of technology and social justice, love weird science facts, and my dog, Coco; a cute black lab/pit bull mix, who won't stop eating rocks.

Leave a comment