How to Use the Ruby map! Method

09/25/2021

Contents

In this article, you will learn how to use the Ruby map! method.

Using the map! method

The map! method in Ruby is a destructive method that is used to transform the elements of an array according to a specified block of code. The original array is replaced with the new transformed array.

Syntax

array.map! { |item| block }

The map! method is called on an array, and a block is passed as an argument. The block is executed for each element of the array, and the result is returned in a new array.

Examples

Example1

fruits = ["apple", "banana", "orange"]
fruits.map! { |fruit| fruit.upcase }

In this example, the map! method is called on the fruits array, and a block is passed that uses the upcase method to transform each element to uppercase. The fruits array is now modified to contain the new transformed elements.

Example2

numbers = [1, 2, 3, 4, 5]
numbers.map! { |num| num * 2 }

In this example, the map! method is called on the numbers array, and a block is passed that multiplies each element by 2. The numbers array is now modified to contain the new transformed elements.

Example3

One important thing to note about the map! method is that it returns the modified array. So, you can also assign the result to a new variable if you want to keep the original array intact.

numbers = [1, 2, 3, 4, 5]
new_numbers = numbers.map! { |num| num * 2 }

In this example, the map! method is called on the numbers array, and the result is assigned to the new_numbers variable. The numbers array is modified, and the new_numbers array contains the transformed elements.