Enumerable Patterns
Reduce Inject
reduce and inject accumulate collection values into one result.
Reduce Inject
reduce_inject.rb
starting_total =
scores = [3, 4, 5]
total = scores.reduce(starting_total) do |sum, score|
sum + score
end
puts "starting_total=#{starting_total}"
puts "scores=#{scores.join(",")}"
puts "total=#{total}"
starting_total =
scores = [3, 4, 5]
total = scores.reduce(starting_total) do |sum, score|
sum + score
end
puts "starting_total=#{starting_total}"
puts "scores=#{scores.join(",")}"
puts "total=#{total}"
starting_total =
scores = [3, 4, 5]
total = scores.reduce(starting_total) do |sum, score|
sum + score
end
puts "starting_total=#{starting_total}"
puts "scores=#{scores.join(",")}"
puts "total=#{total}"
reduce
`reduce` passes the accumulated value and the next item to the block each step.