Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Ruby Dictionary

  1. Home
  2. Ruby Dictionary
  3. Array.reduce / inject

Array.reduce / inject

A method that processes array elements in order and combines them into a single value. Useful for aggregation operations such as sums, products, and finding maximum values.

Syntax

# Performs a fold operation using a block (no initial value).
array.reduce { |accumulator, element| operation }
array.inject { |accumulator, element| operation }  # alias for reduce

# Specifies an initial value.
array.reduce(initial_value) { |accumulator, element| operation }
array.inject(initial_value) { |accumulator, element| operation }

# Specifies an operator using a symbol (initial value is optional).
array.reduce(:operator)
array.reduce(initial_value, :operator)

Method List

MethodDescription
reduce { |acc, e| }Processes each element with the accumulator using a block from left to right, and returns the final accumulated value.
inject { |acc, e| }An alias for reduce. Behaves identically.
reduce(init) { |acc, e| }Starts the fold with a specified initial value. Returns the initial value if the array is empty.
reduce(:+)Specifies an operator using a symbol. reduce(:+) computes the sum; reduce(:*) computes the product.

Sample Code

numbers = [1, 2, 3, 4, 5]

# Computes the sum (no initial value: the first element is used as the starting accumulator).
sum = numbers.reduce { |acc, n| acc + n }
puts sum  # 15

# A shorter way using a symbol.
puts numbers.reduce(:+)  # 15
puts numbers.reduce(:*)  # 120 (product)

# Specifies an initial value.
sum2 = numbers.reduce(100) { |acc, n| acc + n }
puts sum2  # 115 (100 + 1 + 2 + 3 + 4 + 5)

# inject works the same way.
max = numbers.inject { |max, n| n > max ? n : max }
puts max  # 5

# Can also be used for string concatenation.
words = ["Ruby", "is", "fun"]
sentence = words.inject { |acc, w| "#{acc} #{w}" }
puts sentence  # Ruby is fun

# Can be used to convert to a hash.
pairs = [[:name, "Alice"], [:age, 30]]
hash = pairs.reduce({}) { |h, (k, v)| h[k] = v; h }
puts hash.inspect  # {:name=>"Alice", :age=>30}

Overview

reduce (also known as inject) is a method that performs a fold operation on an array. The first block argument is the accumulator, and the second is the current element. The return value of the block becomes the next accumulator.

If no initial value is given, the first element of the array is used as the starting accumulator. Calling this method on an empty array without an initial value raises a TypeError. Always provide an initial value if the array could be empty.

For simple sums, the 'sum' method is more concise. When transformation is needed, consider combining it with 'map', or use each_with_object when the accumulator is an object.

If you find any errors or copyright issues, please .