0
0
Rubyprogramming~15 mins

Why Ruby prefers iterators over loops - See It in Action

Choose your learning style9 modes available
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 1
Use the each iterator on fruits with a block variable fruit to print the index and fruit name, then increment index by 1
Print 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
1
Create the fruits array
Create an array called fruits with these exact values: 'apple', 'banana', 'cherry'
Ruby
Need a hint?

Use square brackets [] to create an array and separate items with commas.

2
Set up the index counter
Create a variable called index and set it to 1
Ruby
Need a hint?

Just write index = 1 to start counting from 1.

3
Use the each iterator to print fruits with index
Use the each iterator on fruits with a block variable fruit to print the index and fruit name, then increment index by 1 inside the block
Ruby
Need a hint?

Use fruits.each do |fruit| ... end and inside the block print the index and fruit, then add index += 1.

4
Display the final output
Run the program to print the fruits with their index using the iterator
Ruby
Need a hint?

Just run the program. You should see each fruit printed with its number.