[RUBY] About the map method

About the map method

The map method returns the result of evaluating the block for each element as a new array. The alias method is the collect method.

(Example) Code that creates a new array by trebling each element of the array

numbers = [1,2,3]
new_numbers = []
numbers.each { |n| new_numbers << n * 3 }
new_numbers #=> [3, 6, 9]

The map method creates a new array in which the return value of the block is an element of the array, so you can just put the return value of the map method into a new variable.

numbers = [1,2,3]
#The return value of the block becomes each element of the new array
new_numbers = numbers.map { |n| n * 3 }
new_numbers #=> [3, 6, 9]

In this way, you can use the map method to replace most of the work of preparing an empty array, looping through other arrays, and packing the results into an empty array.

Referenced literature

Introduction to Ruby for those who want to become professionals

Recommended Posts

About the map method
About the method
Output about the method # 2
About the length method
About the authenticate method.
About the ancestors method
About the to_s method.
Output about the method Part 1
Consideration about the times method
About the role of the initialize method
[Practice] Map method
About the package
ruby map method
[Rails] How to use the map method
About No Method Error
About the StringBuilder class
Commentary: About the interface
About the asset pipeline
About the function double-java
About Java method binding
Stream API map method
About method splitting (Java)
About the Kernel module
[Output] About the database
About the [ruby] operator
About the handling of Null
About specifying the JAXRS path
Note the StringUtils # containsAny method
What is the pluck method?
A note about the scope
About the description of Docker-compose.yml
About the File :: Stat class
Understand the helper method form_with
About the same and equivalent
About the Android life cycle
About the explanation about functional type
About the programming language Crystal
SwiftUI-Display the map using MapKit
About Rails scraping method Mechanize
What is the initialize method?
[Ruby] Questions and verification about the number of method arguments
About the behavior when doing a file map with java
How to use the link_to method
Simulate the simplex method with GUI
About the language to be learned
How to use the include? method
How to use the form_with method
About the basics of Android development
[Rails] About the Punk List function
About the equals () and hashcode () methods
About the symbol <%%> in Rails erb
About the information sharing app band
I tried to explain the method
A murmur about the utility class
[Rails] About helper method form_with [Basic]
About =
Was that so, the user_signed_in? method
Summary about the introduction of Device
About the log level of java.util.logging.Logger
Call the super method in Java