[Ruby] ruby map method

less than 1 minute read

What is the map method?

A method that makes changes to an array and returns the array.

How to write

object.map { |variable|
  #The process you want to execute
}

Or

object.map(&:Method name)

Execution example

In case of writing method 1

a=[2,5,3]

b=a.map{ |hoge| 

  hoge*2   
}

#Result b=[4,10,6]

First, 2 in a [0] is assigned to hoge. And with hoge * 2, 4 goes into b [0].
Then 5 in a [1] is assigned to hoge. And with hoge * 2, 10 goes into b [1].
Finally, 3 in a [2] is assigned to hoge. And with hoge * 2, 6 goes into b [2].

The result is an array b = [4,10,6].

How to write 2 Object.map (&: method name) example

a=["Apple","Spotted seal","Deer"]

b=a.map(&:length)

Result b=[3,7,2]

The length method is a method that returns the length of a string.

Tags:

Updated: