Challenge - 5 Problems
Inject Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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
Attempts:
2 left
💡 Hint
Remember that inject starts with the initial value and adds each element multiplied by 2.
✗ Incorrect
The inject starts at 0. Then it adds 1*2=2, then 2*2=4, then 3*2=6, then 4*2=8. Sum is 2+4+6+8=20.
❓ Predict Output
intermediate2: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
Attempts:
2 left
💡 Hint
Each word is converted to uppercase before adding to the accumulator.
✗ Incorrect
The accumulator starts as an empty string. Each word is upcased and concatenated: '' + 'A' + 'B' + 'C' = 'ABC'.
❓ Predict Output
advanced2: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
Attempts:
2 left
💡 Hint
Count how many numbers are even (key 0) and odd (key 1).
✗ Incorrect
Numbers 2 and 4 are even (key 0), count 2. Numbers 1 and 3 are odd (key 1), count 2.
❓ Predict Output
advanced2: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
Attempts:
2 left
💡 Hint
The + operator concatenates arrays in Ruby.
✗ Incorrect
Starting with empty array, each sub-array is concatenated: [] + [1,2] = [1,2], then + [3,4] = [1,2,3,4], then + [5] = [1,2,3,4,5].
❓ Predict Output
expert3: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
Attempts:
2 left
💡 Hint
The inner inject calculates factorial for each number.
✗ Incorrect
For each n, inner inject calculates factorial: 2! = 2, 3! = 6, 4! = 24. These are stored as values in the hash with keys n.