Reduce (also called inject) helps you combine all items in a list into one value, like adding numbers or joining words.
Reduce/inject for accumulation in Ruby
array.reduce(initial_value) { |accumulator, item| # combine accumulator and item } # or using inject (same as reduce) array.inject(initial_value) { |accumulator, item| # combine accumulator and item }
The accumulator starts with initial_value and updates with each item.
You can omit initial_value, then the first item is used as the start.
[1, 2, 3, 4].reduce(0) { |sum, n| sum + n }
[1, 2, 3, 4].inject(1) { |product, n| product * n }
["a", "b", "c"].reduce("") { |str, ch| str + ch }
[5, 3, 8, 2].reduce { |max, n| n > max ? n : max }
This program shows how to add numbers, multiply them, join words, and find the biggest number using reduce/inject.
numbers = [10, 20, 30, 40] sum = numbers.reduce(0) { |total, num| total + num } product = numbers.inject(1) { |total, num| total * num } words = ["Ruby", " ", "is", " ", "fun"] sentence = words.reduce("") { |str, word| str + word } max_num = numbers.reduce { |max, num| num > max ? num : max } puts "Sum: #{sum}" puts "Product: #{product}" puts "Sentence: '#{sentence}'" puts "Max number: #{max_num}"
Reduce and inject are the same method; you can use either name.
Always think about what your starting value (initial_value) should be.
If you forget the initial value, the first item is used as the start, so the block runs one less time.
Reduce/inject combines all items in a list into one value.
You provide a starting value and a block to tell how to combine.
It works great for sums, products, joining strings, or finding max/min.
Practice
inject do when used on an array?Solution
Step 1: Understand the purpose of
Theinjectinjectmethod takes all elements of an array and combines them into one value using the block provided.Step 2: Compare with other options
Sorting, removing duplicates, or returning the first element are different methods likesort,uniq, orfirst.Final Answer:
It combines all elements into a single value using a block. -> Option AQuick Check:
inject combines elements = C [OK]
- Confusing inject with sorting methods
- Thinking inject returns an array
- Assuming inject removes duplicates
arr using inject?Solution
Step 1: Identify the correct initial value and operation
To sum elements, start with 0 and add each element:inject(0) { |sum, n| sum + n }.Step 2: Check other options
arr.inject { |sum, n| sum - n } subtracts, C multiplies starting at 1, A divides. Only D sums correctly.Final Answer:
arr.inject(0) { |sum, n| sum + n } -> Option BQuick Check:
Sum with inject = D [OK]
- Starting sum with 1 instead of 0
- Using wrong operation like subtraction
- Omitting initial value causing errors
numbers = [2, 3, 4]
result = numbers.inject(1) { |product, n| product * n }
puts resultSolution
Step 1: Understand the initial value and operation
The initial value is 1, and each element multiplies the accumulator: 1*2=2, 2*3=6, 6*4=24.Step 2: Calculate the final product
The final result after all multiplications is 24.Final Answer:
24 -> Option DQuick Check:
2*3*4 = 24 [OK]
- Adding instead of multiplying
- Starting with 0 causing zero result
- Confusing output with sum
arr = [1, 2, 3]
sum = arr.inject { |total, n| total + n }
puts sumSolution
Step 1: Check if initial value is required
When no initial value is given, inject uses the first element as the start and iterates from the second element.Step 2: Verify the sum calculation
It correctly sums 1 + 2 + 3 = 6 without error.Final Answer:
No error; code works fine. -> Option AQuick Check:
inject without initial value sums correctly = A [OK]
- Assuming initial value is always required
- Thinking block parameters order is wrong
- Believing inject needs symbol argument
:name and :price, how can you use inject to find the total price of all products?
products = [
{ name: "Book", price: 12 },
{ name: "Pen", price: 3 },
{ name: "Notebook", price: 7 }
]Solution
Step 1: Access the price key correctly
Each product is a hash, so access price withproduct[:price].Step 2: Sum prices starting at 0
Start with 0 and add each price to get total price.Step 3: Check other options
products.inject { |total, product| total + product.name } uses dot notation which is invalid for hashes, C multiplies prices, D uses dot notation again.Final Answer:
products.inject(0) { |total, product| total + product[:price] } -> Option CQuick Check:
Sum prices with inject and hash keys = B [OK]
- Using dot notation for hash keys
- Multiplying prices instead of summing
- Starting sum at 1 instead of 0
Ready to prove it?
Pass the test and this pattern moves unknown
