Recall & Review
beginner
What does the
reduce (or inject) method do in Ruby?It combines all elements of a collection by applying a block or operation, accumulating a single result.
Click to reveal answer
beginner
How do you start an accumulation with a specific initial value using
reduce?Pass the initial value as an argument to
reduce, like array.reduce(0) { |sum, n| sum + n }.Click to reveal answer
beginner
What is the difference between
reduce and inject in Ruby?There is no difference;
inject is an alias for reduce.Click to reveal answer
beginner
Example: What does
[1, 2, 3].reduce(:+) return?It returns
6, the sum of all elements.Click to reveal answer
intermediate
Can
reduce be used to accumulate non-numeric results? Give an example.Yes. For example,
['a', 'b', 'c'].reduce('') { |acc, s| acc + s } returns 'abc' by joining strings.Click to reveal answer
What is the purpose of the
reduce method in Ruby?✗ Incorrect
reduce combines elements to produce one result, like a sum or product.
How do you specify an initial value for accumulation with
reduce?✗ Incorrect
You pass the initial value directly, e.g.,
reduce(0).What will
[2, 3, 4].reduce(1) { |product, n| product * n } return?✗ Incorrect
It multiplies all elements starting from 1: 1*2*3*4 = 24.
Which method is an alias for
reduce in Ruby?✗ Incorrect
inject is exactly the same as reduce.Can
reduce be used to concatenate strings?✗ Incorrect
You can accumulate strings by joining them inside the block.
Explain how
reduce works for accumulating values in a Ruby array.Think about how you add or multiply all elements step by step.
You got /4 concepts.
Give an example of using
reduce to join an array of strings into one string.Start with an empty string and add each element.
You got /4 concepts.