0
0
Rubyprogramming~20 mins

Each as the primary iterator in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Each Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A[2, 4, 6]
B[1, 2, 3]
Cnil
D[3, 6, 9]
Attempts:
2 left
💡 Hint
Remember that each goes through every element and you can collect results in another array.
Predict Output
intermediate
2: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}"
end
A
a:3
b:2
B
a:1
b:2
C
a:1
b:6
D
a:3
b:6
Attempts:
2 left
💡 Hint
Each goes through each key-value pair. Value is multiplied by 3 in the output.
🔧 Debug
advanced
2: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
ABecause x is a copy of each element, modifying x does not change the array elements.
BBecause each does not run the block at all.
CBecause x is a reference to the array element and changes should reflect.
DBecause the array is frozen and cannot be changed.
Attempts:
2 left
💡 Hint
Think about whether changing the block variable changes the original array element.
📝 Syntax
advanced
2: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
A
arr.each |x| do
  puts x
end
B
arr.each do |x|
  puts x
end
C
arr.each do |x|
  puts x
D
arr.each do x |
  puts x
end
Attempts:
2 left
💡 Hint
Remember the syntax for blocks with do...end and pipes for block variables.
🚀 Application
expert
2: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
A4
B2
C3
D5
Attempts:
2 left
💡 Hint
Check which numbers in the array are even and count them.