Why Ruby Prefers Iterators Over Loops
📖 Scenario: Imagine you have a list of fruits and you want to print each fruit's name. In Ruby, you can do this using loops or iterators. Ruby prefers iterators because they are simpler and safer to use.
🎯 Goal: You will create a list of fruits, set up a counter, use an iterator to print each fruit with its position, and finally display the output.
📋 What You'll Learn
Create an array called
fruits with these exact values: 'apple', 'banana', 'cherry'Create a variable called
index and set it to 1Use the
each iterator on fruits with a block variable fruit to print the index and fruit name, then increment index by 1Print the output exactly as shown
💡 Why This Matters
🌍 Real World
Iterators are used in Ruby programs to process lists of data like user names, product lists, or messages efficiently and clearly.
💼 Career
Understanding iterators helps you write clean, maintainable Ruby code, which is essential for Ruby developers working on web apps, automation scripts, or data processing.
Progress0 / 4 steps