reduce
Quiz
What does [24, 6, 2].reduce(:/)
return?
0
1
2
[48, 2, 0, 0]
/
operator, updating the accumulator with each iteration. This invocation of reduce
is equivalent to 24 / 6 / 2
, which returns 2
.What does [24, 6, 2].reduce {|acc, el| acc / el}
return?
0
1
2
[48, 2, 0, 0]
reduce
is functionally equivalent to the previous because the block simply invokes the /
operator.What does [24, 6, 2].reduce {|acc, el| acc / el - 1}
return?
0
1
2
[48, 2, 0, 0]
24
. The first iteration reassigns the accumulator to 3
(24 / 6 - 1
). The second and final iteration reassigns the accumulator to 0
(3 / 2 - 1
). (The block decrements one on each iteration, not just the final one.) What does [24, 6, 2].reduce(48) {|acc, el| acc / el}
return?
0
1
2
[48, 2, 0, 0]
48
. The first iteration reassigns the accumulator to 2
(48 / 24
). The second reassigns the accumulator to 0
(2 / 6
). The third and final again reassigns the accumulator to 0
(0 / 2
).What does [24, 6, 2].reduce([48]) {|acc, el| acc << acc.last / el}
return?
0
1
2
[48, 2, 0, 0]
[48]
as the initial accumulator. The first iteration reassigns the accumulator to [48, 2]
([48] << 48 / 24
). The second reassigns the accumulator to [48, 2, 0]
([48, 2] << 2 / 6
). The third and final reassigns the accumulator to [48, 2, 0, 0]
([48, 2, 0] << 0 / 2
).