Challenge - 5 Problems
Each Mastery Badge
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 do |x| result << x * 2 end puts result.inspect
Attempts:
2 left
💡 Hint
Remember that each goes through every element and you can collect results in another array.
✗ Incorrect
The each method goes through each element in arr. For each element x, it multiplies by 2 and adds to result. So result becomes [2, 4, 6].
❓ Predict Output
intermediate2:00remaining
Each with hash iteration output
What will this Ruby code print?
Ruby
h = {a: 1, b: 2}
h.each do |key, value|
puts "#{key}:#{value * 3}"
endAttempts:
2 left
💡 Hint
Each goes through each key-value pair. Value is multiplied by 3 in the output.
✗ Incorrect
The each method iterates over each key-value pair. For each, it prints key and value multiplied by 3. So a:3 and b:6 are printed.
🔧 Debug
advanced2:00remaining
Why does this each loop not modify the array?
Look at this Ruby code. Why does the array stay the same after the each loop?
Ruby
arr = [1, 2, 3] arr.each do |x| x = x * 10 end puts arr.inspect
Attempts:
2 left
💡 Hint
Think about whether changing the block variable changes the original array element.
✗ Incorrect
In Ruby, the block variable x is a copy of the element's value. Assigning x = x * 10 changes only x, not the original array element. So arr stays [1, 2, 3].
📝 Syntax
advanced2:00remaining
Identify the syntax error in this each block
Which option shows the correct way to write this each block without syntax errors?
Ruby
arr = [1, 2, 3] arr.each do |x| puts x
Attempts:
2 left
💡 Hint
Remember the syntax for blocks with do...end and pipes for block variables.
✗ Incorrect
Option B correctly uses do |x| ... end. Option B has wrong order of pipes and do. Option B misses end. Option B has misplaced pipe.
🚀 Application
expert2:00remaining
Count how many elements are even using each
Using each as the primary iterator, what is the value of count after running this code?
Ruby
arr = [4, 7, 10, 3, 6] count = 0 arr.each do |num| count += 1 if num.even? end puts count
Attempts:
2 left
💡 Hint
Check which numbers in the array are even and count them.
✗ Incorrect
The even numbers are 4, 10, and 6. So count increases 3 times. The final count is 3.