Ruby - map Function Example

1. Introduction

The map function is a versatile and commonly-used method in Ruby that allows for concise and expressive transformations of collections. In this post, we'll delve deep into the map function, covering its various use cases and how to leverage its capabilities in Ruby.

The map function, available on arrays and other enumerable objects in Ruby, processes each element of the collection using the provided block of code and returns a new array with the results. It does not modify the original collection.

2. Program Steps

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

2. Use the map function to perform various transformations.

3. Print the results.

3. Code Program

# Step 1: Define an array of numbers
numbers = [1, 2, 3, 4, 5]
# Step 2a: Use map to square each number
squared = numbers.map { |num| num * num }
# Step 2b: Use map to convert each number to a string
as_strings = numbers.map(&:to_s)
# Step 2c: Use map to determine if each number is even
is_even = numbers.map { |num| num.even? }
# Step 3: Print the results
puts "Original Numbers: #{numbers}"
puts "Squared Numbers: #{squared}"
puts "Numbers as Strings: #{as_strings}"
puts "Is Number Even?: #{is_even}"

Output:

Original Numbers: [1, 2, 3, 4, 5]
Squared Numbers: [1, 4, 9, 16, 25]
Numbers as Strings: ["1", "2", "3", "4", "5"]
Is Number Even?: [false, true, false, true, false]

Explanation:

1. numbers: This is our initial array containing a set of integers.

2. squared: This new array is derived by squaring each element of the numbers array.

3. as_strings: Another transformation, where each number from the original numbers array is converted into a string.

4. is_even: This demonstrates a boolean use case, where we determine if each number in the original array is even or not.

5. The &:method_name syntax in numbers.map(&:to_s) is a shorthand in Ruby which passes :method_name as a block to the map function. This is a succinct way to call a method on each element of the array.

The map function offers an elegant way to perform a variety of operations on collections in Ruby, making code more readable and expressive.


Comments