0
0
Rubyprogramming~5 mins

Reduce/inject for accumulation in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ATo create a new array with transformed elements
BTo combine all elements of a collection into a single value
CTo filter elements based on a condition
DTo sort elements in ascending order
How do you specify an initial value for accumulation with reduce?
ABy calling <code>initialize</code> method
BBy setting a global variable
CBy passing it as an argument to <code>reduce</code>
DBy using <code>map</code> before <code>reduce</code>
What will [2, 3, 4].reduce(1) { |product, n| product * n } return?
A9
BNone of the above
C10
D24
Which method is an alias for reduce in Ruby?
Ainject
Bmap
Cselect
Deach
Can reduce be used to concatenate strings?
AYes, by accumulating strings
BNo, it only works with numbers
COnly if you convert strings to numbers first
DOnly with arrays of integers
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.