📖 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
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
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
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
Hint
Just run the program. You should see each fruit printed with its number.
Practice
(1/5)
1. Why does Ruby prefer using iterators like each over traditional loops like for?
easy
A. Because iterators make code simpler and easier to read
B. Because loops are faster in Ruby
C. Because loops use less memory
D. Because iterators require more lines of code
Solution
Step 1: Understand Ruby's design philosophy
Ruby emphasizes writing clear and readable code that is easy to maintain.
Step 2: Compare iterators and loops
Iterators like each abstract away loop details, making code simpler and less error-prone than traditional loops.
Final Answer:
Because iterators make code simpler and easier to read -> Option A
2. Which of the following is the correct syntax for iterating over an array arr in Ruby?
easy
A. for i in arr puts i end
B. arr.each { |item| puts item }
C. arr.loop { |item| puts item }
D. arr.iterate do |i| puts i end
Solution
Step 1: Identify valid Ruby iterator syntax
The method each is the standard iterator for collections in Ruby.
Step 2: Check each option
arr.each { |item| puts item } uses arr.each { |item| puts item }, which is correct syntax. The for loop "for i in arr puts i end" has invalid syntax (missing 'do'), options C and D use invalid method names.
Final Answer:
arr.each { |item| puts item } -> Option B
Quick Check:
Correct iterator syntax = A [OK]
Hint: Look for each with block syntax for iteration [OK]
Common Mistakes:
Using non-existent methods like loop or iterate
Confusing loops with iterators
Missing block syntax with pipes | |
3. What will be the output of this Ruby code?
numbers = [1, 2, 3]
numbers.each do |n|
puts n * 2
end
medium
A. 2
4
6
B. 1
2
3
C. Error: undefined method each
D. nil
Solution
Step 1: Understand the iterator behavior
The each method goes through each element in the array numbers.
Step 2: Calculate output for each iteration
For each number n, it prints n * 2. So outputs are 2, 4, and 6 on separate lines.
Final Answer:
2
4
6 -> Option A
Quick Check:
Each number doubled = C [OK]
Hint: Multiply inside each block to get doubled output [OK]
Common Mistakes:
Expecting original numbers instead of doubled
Thinking each returns an array
Confusing output with error messages
4. Identify the error in this Ruby code using an iterator:
items = ["a", "b", "c"]
items.each do item
puts item
end
medium
A. Incorrect method name, should be for_each
B. No error, code runs fine
C. Array items cannot be iterated
D. Missing block parameter pipes | | around item
Solution
Step 1: Check block parameter syntax
In Ruby, block parameters must be enclosed in pipes, like |item|.
Step 2: Identify the missing pipes
The code uses do item instead of do |item|, causing a syntax error.
Final Answer:
Missing block parameter pipes | | around item -> Option D
Quick Check:
Block parameters need | | = B [OK]
Hint: Always use |param| in blocks for iterators [OK]
Common Mistakes:
Omitting pipes around block variables
Using wrong method names
Assuming arrays can't be iterated
5. Given a hash scores = { alice: 10, bob: 15, carol: 7 }, how can you use an iterator to create a new hash with only scores greater than 8?
hard
A. scores.map { |name, score| score > 8 }
B. scores.each { |name, score| score > 8 }
C. scores.select { |name, score| score > 8 }
D. scores.filter { |name, score| score < 8 }
Solution
Step 1: Understand the goal
We want a new hash with only entries where the score is greater than 8.
Step 2: Choose the right iterator method
select filters a hash by condition and returns a new hash with matching pairs.
Step 3: Check each option
scores.select { |name, score| score > 8 } uses select with correct condition. scores.each { |name, score| score > 8 } uses each which returns original hash, not filtered. scores.map { |name, score| score > 8 } uses map which returns an array of booleans. scores.filter { |name, score| score < 8 } filters for scores less than 8, opposite of requirement.