Ruby - reduce Function Example

1. Introduction

The reduce function, also known as inject, is a powerful method in Ruby that facilitates the process of condensing a collection into a single accumulated result. In this article, we'll dive into the reduce function, highlighting its multiple use cases and showcasing its potential within Ruby programming.

2. Program Steps

1. Define an initial collection, such as an array of numbers.

2. Apply the reduce function to perform various accumulations.

3. Print the results.

3. Code Program

# Step 1: Define an array of numbers
numbers = [1, 2, 3, 4, 5]
# Step 2a: Use reduce to compute the sum of the numbers
sum = numbers.reduce(0) { |accumulator, num| accumulator + num }
# Step 2b: Use reduce to find the product of the numbers
product = numbers.reduce(1) { |accumulator, num| accumulator * num }
# Step 2c: Use reduce to determine the maximum number
max_num = numbers.reduce { |max, num| max > num ? max : num }
# Step 3: Print the results
puts "Numbers: #{numbers}"
puts "Sum of Numbers: #{sum}"
puts "Product of Numbers: #{product}"
puts "Maximum Number: #{max_num}"

Output:

Numbers: [1, 2, 3, 4, 5]
Sum of Numbers: 15
Product of Numbers: 120
Maximum Number: 5

Explanation:

1. numbers: This is our foundational array consisting of integers.

2. sum: Using reduce, we begin with an initial accumulator value of 0. In each iteration, we add the current number (num) to the accumulator.

3. product: Similarly, we start with an accumulator value of 1 and multiply it with each number in the sequence.

4. max_num: This showcases a use case without an initial accumulator. The first element becomes the initial accumulator by default. We then compare the accumulator (max) with each element and keep the larger value.

5. The reduce function provides a unified and streamlined approach to achieve a variety of operations, like summing elements, finding products, or determining maximum and minimum values.

The reduce method is available for arrays and other enumerable objects in Ruby. It iteratively processes each element of the collection using an accumulator and the element. The result from each iteration becomes the accumulator for the next iteration. The method finally returns the accumulated result.


Comments