All original content is created in Ukrainian. Not all content has been translated yet. Some posts may only be available in Ukrainian.Learn more

How does the map method work in Ruby? Overview of the method's operation with examples

Post cover: How does the map method work in Ruby? Overview of the method's operation with examples
Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
The map method is one of the most commonly used methods in Ruby, used for processing collections. It allows you to apply a block of code to each element of the collection and return a new collection with the results of the block execution. That's actually all the explanation. However, any information is better understood not through abstractions but through simple and real examples. So let's take a closer look at the map method.

How map works

The map method takes a block that is executed for each element of the collection. The results of executing this block are collected into a new array, which is returned by the map method.
Let's increment each element of the array by 1.
numbers = [1, 2, 3, 4, 5]
incremented_numbers = numbers.map { |n| n + 1 }

incremented_numbers

Result
=> [2, 3, 4, 5, 6]
To simplify:
We have a variable numbers that contains an array of elements (a collection of elements) [1, 2, 3, 4, 5].
Next, we create a variable incremented_numbers and assign to it the result of executing the map method.
Let's consider the map construct:
numbers.map { |n| n + 1 }

# numbers - our variable (collection)
# .map - method call on the variable
# { |n| n + 1 } - block that will be executed for each element of the collection
Here we need to consider the block itself:
{ |n| n + 1 }
  • {} - curly braces: This is the body of the block, where the code that will be executed for each element of the array is located.
  • |n| - variable: This is the parameter of the block. Each element of the array is passed to this variable one by one.
  • n + 1: This is the expression that is executed for each element. It adds 1 to the value of the variable n.
When we execute numbers.map { |n| n + 1 }, here's what happens:
For the first element 1:
  • n becomes 1
  • 1 + 1 is executed
  • The result 2 is added to the new array
For the second element 2:
  • n becomes 2
  • 2 + 1 is executed
  • The result 3 is added to the new array
And so on for each element of the array. The new array is stored in the variable incremented_numbers and we check its content
numbers = [1, 2, 3, 4, 5]
incremented_numbers = numbers.map { |n| n + 1 }
incremented_numbers

Result
=> [2, 3, 4, 5, 6]
What will happen to the variable numbers? Nothing, it remains unchanged.
Another example:
words = ["hello", "world", "ruby"]
new_words = words.map { |word| word.upcase }

new_words
=> ["HELLO", "WORLD", "RUBY"]
words
=> ["hello", "world", "ruby"]
The upcase method modifies letters (makes them uppercase). So the new_words variable contains modified words, while words remains unchanged.
By the way, in these examples we use the block construct in curly braces. The block can also be passed using do ... end (in cases where the code is too long and it would be good to split it into several lines). That is:
numbers.map { |n| n + 1 }

is the same as

numbers.map do |n| 
  n + 1
end
And an example of passing the result into a variable:
incremented_numbers_braces = numbers.map { |n| n + 1 }

incremented_numbers_do_end = numbers.map do |n| 
  n + 1
end
Another example, but we will modify a hash
hash = { a: 1, b: 2, c: 3 }
incremented_hash = hash.map { |key, value| [key, value + 1] }

incremented_hash
=> [[:a, 2], [:b, 3], [:c, 4]]
But there is a nuance. The execution of map returns an Array. So we need to convert the Array into a Hash (using the .to_h method).
incremented_hash = incremented_hash.to_h

incremented_hash
=> {:a=>2, :b=>3, :c=>4}
I think it is quite clear in the construct hash.map { |key, value| [key, value + 1] } that we take key and value from each element of the hash and return a construct like [key, value + 1].
That is, the result of executing map for an element will return an array where the first element is key and the second is the modified value (value + 1).
The result of execution on the entire collection is as follows:
incremented_hash
=> [[:a, 2], [:b, 3], [:c, 4]]
An array of arrays. Which we then convert into a hash (calling to_h).

map! - modifies the original array

The exclamation mark added to the map method means that the original collection (variable) will be modified. This type of method call should be used with caution.
numbers = [1, 2, 3, 4, 5]
numbers.map! { |n| n + 1 }

numbers
=> [2, 3, 4, 5, 6]
  • map: Creates a new array, leaving the original array unchanged.
  • map!: Modifies the original array, changing its elements in place.

Why is the method called (map)?

The name map comes from the mathematical operation "mapping," where each element of one set is "mapped" to the corresponding element of another set. In programming, this means applying a function or block of code to each element of a collection to create a new collection with the results of these applications.
The map method in Ruby is a powerful tool for processing collections, allowing you to easily create new collections by transforming each element using a specified block. It has additional capabilities (such as using indices), alternatives (such as each), and even synonyms (collect). But the purpose of this post was to explain the principle of how the map method works without strong complications. Other things will be discussed in future posts about Ruby.

This post doesn't have any additions from the author yet.

How to make an empty git commit?
28 Jun 08:33

How to make an empty git commit?

meme code
meme code@memecode
Ruby library Gosu for creating 2D games
29 Jun 08:48

Ruby library Gosu for creating 2D games

meme code
meme code@memecode
Gosu Ruby Tutorial - пройдемось по офіційній документації
03 Jul 11:50

Gosu Ruby Tutorial - пройдемось по офіційній документації

meme code
meme code@memecode
We are writing a demo game Drones vs Zombies (Gosu / Ruby)
12 Jul 12:17

We are writing a demo game Drones vs Zombies (Gosu / Ruby)

meme code
meme code@memecode
How to fix a Windows crash caused by CrowdStrike?
19 Jul 13:53

How to fix a Windows crash caused by CrowdStrike?

meme code
meme code@memecode
What does .map(&:name) mean in Ruby?
28 Jul 11:18

What does .map(&:name) mean in Ruby?

meme code
meme code@memecode
What does a dot at the beginning of a file (.gitignore, .DS_Store, .bashrc, etc.) mean?
02 Aug 13:15

What does a dot at the beginning of a file (.gitignore, .DS_Store, .bashrc, etc.) mean?

meme code
meme code@memecode
What is .gitignore? What is it for and how to use it
02 Aug 14:58

What is .gitignore? What is it for and how to use it

meme code
meme code@memecode
How to remove the .DS_Store file from a Git repository?
02 Aug 19:34

How to remove the .DS_Store file from a Git repository?

meme code
meme code@memecode
What is an idempotent method?
21 Aug 20:57

What is an idempotent method?

meme code
meme code@memecode
What is a repository?
21 Aug 21:25

What is a repository?

meme code
meme code@memecode
What is a commit in the context of programming and SCM / Git?
21 Aug 21:37

What is a commit in the context of programming and SCM / Git?

meme code
meme code@memecode