Loop Controls - break, next
Dive into Loop Controls
Welcome back! You've already learned the basics of loops in Ruby and how to iterate through collections using for and each loops. Now, let's take it one step further. In this lesson, we'll explore loop controls, specifically break and next. These powerful tools give you finer control over your loops, making your code even more efficient and flexible.
What You'll Learn
In this lesson, you'll discover how to use break to exit a loop early and next to skip to the next iteration in a loop. These controls can make your loops more sophisticated and adaptable to different scenarios.
Here's a sneak peek at what we'll cover:
Let's break down the code for better understanding:
-
Initialization:
- We create an array called
shopping_listcontaining several items. - We set a variable
max_itemsto 4, indicating the maximum number of items we want to process. - We initialize
items_processedto 0 to keep track of how many items have been processed.
- We create an array called
-
Loop Through Items:
- The
eachmethod begins to iterate over each item in theshopping_list.
- The
-
Break Condition:
- The loop checks if
items_processedequalsmax_items. - If true, it prints a message and uses
breakto exit the loop early.
- The loop checks if
-
Increment Processed Items:
items_processedis incremented by 1 on each iteration, keeping track of the number of processed items.
-
Next Condition:
- If the current item is "honey", it prints a message and uses
nextto skip the expiration date check for this iteration, continuing to the next item.
- If the current item is "honey", it prints a message and uses
-
Expiration Date Check:
- If the current item is not "honey", it prints a message checking the expiration date of the item.
