Nested loops

Is it possible to do nested loops? Absolutely! Should you seriously reconsider your code and make sure there’s not another way to do it if you are thinking of using nested loops? ABSOLUTELY! Sometimes you have no choice… but more often, you just need to sit back and think about a better way to do what you want. Here’s a bit of an example:

I work at a nutrition company. We have meal plans, meal plans have recipes, recipes have ingredient measurements, and ingredient measurements have ingredients. In one part of the app, we were trying to consolidate all the ingredients in a meal plan and their measurements. Originally, that involved something like this:

  1. Get all the recipes
  2. Get all the ingredient measurements in that recipe
  3. Get all the ingredients
  4. For each ingredient, get all the ingredient measurements, then loop through those and consolidate

Easier and less memory-intensive way of doing this:

  1. Get all the recipes
  2. Get all the ingredient measurements in that recipe
  3. Loop through those once and tally them up using a hash, so your end result looks like this:
    {'1': [[1, 'cup'], [2, 'ounces']]}