0
0
RubyHow-ToBeginner · 3 min read

How to Use Inject in Ruby: Simple Guide with Examples

In Ruby, inject is a method used to accumulate a single value from elements in a collection by applying a block or symbol operation. You call inject on an enumerable, optionally provide an initial value, and then define how to combine elements step-by-step.
📐

Syntax

The inject method can be used with or without an initial value. It takes either a block or a symbol representing an operation.

  • collection.inject(initial) { |accumulator, element| ... }: Starts with initial as the accumulator.
  • collection.inject { |accumulator, element| ... }: Uses the first element as the initial accumulator.
  • collection.inject(:operation): Uses a symbol like :+ to apply an operation.
ruby
numbers = [1, 2, 3, 4]

# With initial value and block
sum = numbers.inject(0) { |acc, n| acc + n }

# Without initial value
product = numbers.inject { |acc, n| acc * n }

# Using symbol
sum_symbol = numbers.inject(:+)
💻

Example

This example shows how to use inject to sum numbers, multiply them, and concatenate strings.

ruby
numbers = [2, 3, 4]

# Sum with initial value 0
sum = numbers.inject(0) { |acc, n| acc + n }
puts "Sum: #{sum}"

# Product without initial value
product = numbers.inject { |acc, n| acc * n }
puts "Product: #{product}"

# Concatenate strings
words = ['I', 'love', 'Ruby']
sentence = words.inject('') { |acc, word| acc + word + ' ' }.strip
puts "Sentence: '#{sentence}'"
Output
Sum: 9 Product: 24 Sentence: 'I love Ruby'
⚠️

Common Pitfalls

Common mistakes include forgetting the initial value when needed, which can cause errors with empty collections, or mixing up the order of accumulator and element in the block.

Also, using inject without a block or symbol will raise an error.

ruby
# Wrong: no initial value on empty array
empty = []
# empty.inject { |acc, n| acc + n } # Raises LocalJumpError

# Right: provide initial value
sum_empty = empty.inject(0) { |acc, n| acc + n }
puts sum_empty  # Outputs 0

# Wrong: swapping accumulator and element
numbers = [1, 2, 3]
sum_wrong = numbers.inject(0) { |n, acc| n + acc }  # Wrong order
puts sum_wrong  # Outputs 6 but logic is confusing

# Right: correct order
sum_right = numbers.inject(0) { |acc, n| acc + n }
puts sum_right  # Outputs 6
Output
0 6 6
📊

Quick Reference

UsageDescriptionExample
inject(initial) { |acc, elem| ... }Starts with initial accumulator value[1,2,3].inject(0) { |sum, n| sum + n } #=> 6
inject { |acc, elem| ... }Uses first element as initial accumulator[1,2,3].inject { |prod, n| prod * n } #=> 6
inject(:symbol)Uses symbol to apply operation[1,2,3].inject(:+) #=> 6

Key Takeaways

Use inject to combine elements by accumulating a value with a block or symbol.
Provide an initial value to avoid errors with empty collections.
The block receives accumulator first, then the current element.
You can use symbols like :+ or :* for common operations.
inject is powerful for sums, products, concatenations, and more.