Challenge - 5 Problems
Each Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of each with array iteration
What is the output of this Ruby code?
Ruby
arr = [1, 2, 3] result = [] arr.each { |x| result << x * 2 } puts result.inspect
Attempts:
2 left
💡 Hint
Remember that each iterates over elements and you can push transformed values into another array.
✗ Incorrect
The each method goes through each element in arr. For each element x, it multiplies by 2 and appends to result. So result becomes [2, 4, 6].
❓ Predict Output
intermediate2:00remaining
Return value of each method
What does the following Ruby code print?
Ruby
numbers = [10, 20, 30] result = numbers.each { |n| n + 5 } puts result.inspect
Attempts:
2 left
💡 Hint
The each method returns the original array, not the transformed values.
✗ Incorrect
The each method returns the original array it was called on, ignoring the block's return values. So result is [10, 20, 30].
🔧 Debug
advanced2:00remaining
Spot the error in each iteration
Which option will raise an error when trying to print each fruit in uppercase?
Ruby
fruits = ['apple', 'banana', 'cherry'] fruits.each do |fruit| puts fruit.upcase end
Attempts:
2 left
💡 Hint
Check the method name for converting string to uppercase.
✗ Incorrect
The method 'uppercase' does not exist in Ruby String class, so option A causes NoMethodError. The original code is correct and runs without error. Options B, C, and D are valid and produce output. Only A causes error.
📝 Syntax
advanced2:00remaining
Identify the syntax error in each block
Which option contains a syntax error in the each iteration?
Ruby
items = [1, 2, 3]
Attempts:
2 left
💡 Hint
Check the placement of pipes and braces in each block syntax.
✗ Incorrect
Option D is invalid syntax because the pipes |item| must be inside the block delimiters {} or do..end. The correct syntax is either items.each { |item| ... } or items.each do |item| ... end.
🚀 Application
expert2:00remaining
Count elements with each iteration
Using each, how many elements in the array are greater than 5?
Ruby
arr = [3, 7, 2, 9, 5] count = 0 arr.each do |x| count += 1 if x > 5 end puts count
Attempts:
2 left
💡 Hint
Check each number and count only those greater than 5.
✗ Incorrect
Only 7 and 9 are greater than 5, so count is 2.