0
0
Rubyprogramming~20 mins

Reduce/inject for accumulation in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Inject Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code using inject?
Consider the following Ruby code that uses inject to accumulate values. What will be printed?
Ruby
numbers = [1, 2, 3, 4]
result = numbers.inject(0) { |sum, n| sum + n * 2 }
puts result
A24
B10
C20
D16
Attempts:
2 left
💡 Hint
Remember that inject starts with the initial value and adds each element multiplied by 2.
Predict Output
intermediate
2:00remaining
What does this inject code return?
What is the value of result after running this Ruby code?
Ruby
words = ['a', 'b', 'c']
result = words.inject('') { |acc, w| acc + w.upcase }
puts result
Aabc
BError
CaBc
DABC
Attempts:
2 left
💡 Hint
Each word is converted to uppercase before adding to the accumulator.
Predict Output
advanced
2:00remaining
What is the output of this inject with a hash accumulator?
Given this Ruby code, what will be printed?
Ruby
arr = [1, 2, 3, 4]
result = arr.inject(Hash.new(0)) do |hash, n|
  hash[n % 2] += 1
  hash
end
puts result
A{0=>2, 1=>2}
B{0=>1, 1=>3}
C{0=>3, 1=>1}
DTypeError
Attempts:
2 left
💡 Hint
Count how many numbers are even (key 0) and odd (key 1).
Predict Output
advanced
2:00remaining
What does this inject code output when accumulating arrays?
What will be the output of this Ruby code?
Ruby
arrays = [[1, 2], [3, 4], [5]]
result = arrays.inject([]) { |acc, arr| acc + arr }
puts result.inspect
A[1, 2, 3, 4, 5]
B[[1, 2, 3, 4, 5]]
C[[1, 2], [3, 4], [5]]
DTypeError
Attempts:
2 left
💡 Hint
The + operator concatenates arrays in Ruby.
Predict Output
expert
3:00remaining
What is the final value of result after this complex inject?
Analyze this Ruby code using inject with a nested block and determine the final value of result.
Ruby
data = [2, 3, 4]
result = data.inject({}) do |hash, n|
  hash[n] = (1..n).inject(1) { |prod, x| prod * x }
  hash
end
puts result.inspect
ANoMethodError
B{2=>2, 3=>6, 4=>24}
C{2=>2, 3=>3, 4=>4}
D{2=>1, 3=>6, 4=>24}
Attempts:
2 left
💡 Hint
The inner inject calculates factorial for each number.