0
0
Rubyprogramming~20 mins

Each for iteration in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Each Iteration Master
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 { |x| result << x * 2 }
puts result.inspect
A[1, 2, 3]
Bnil
C[2, 4, 6]
D[1, 4, 9]
Attempts:
2 left
💡 Hint
Remember that each iterates over elements and you can push transformed values into another array.
Predict Output
intermediate
2: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
A[15, 25, 35]
B[10, 20, 30]
CTypeError
Dnil
Attempts:
2 left
💡 Hint
The each method returns the original array, not the transformed values.
🔧 Debug
advanced
2: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
A
fruits.each do |fruit|
  puts fruit.uppercase
end
Bfruits.each { |fruit| puts fruit.upcase }
C
fruits.each do |fruit|
  puts fruit.upcase()
end
D
fruits.each do |f|
  puts f.upcase
end
Attempts:
2 left
💡 Hint
Check the method name for converting string to uppercase.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in each block
Which option contains a syntax error in the each iteration?
Ruby
items = [1, 2, 3]
A
items.each do |item|
  puts item
end
Bitems.each do |item| puts item end
Citems.each { |item| puts item }
Ditems.each |item| { puts item }
Attempts:
2 left
💡 Hint
Check the placement of pipes and braces in each block syntax.
🚀 Application
expert
2: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
A2
B3
C4
D5
Attempts:
2 left
💡 Hint
Check each number and count only those greater than 5.