[1, 2, 3].map do |num|
num + 1
end
=> [2, 3, 4]
~ [1,2,3] is the calling object
~ .map is the method
~ do....end is the block
~ [2,3,4] is the return object
So the block is a kind of argument passed into the method. This chunk of code will add to the individual element in the array by 1.
[1,2,3].map(&block)
You are passing in the block as an argument.
What map does is take each element in the array, run it through the block .
It is like the array#include? function, which take each element in the array, then compare it against the argument
[1,2,3].include?(2) then return true. In this case, the argument is just a single number.
But in our case, the argument is a whole chunk of code.
the Map function is to pass in each element into the chunk of code, then make the return value of each block into a new array. Then, return the new array.
~ [1,2,3] is the calling object
~ .map is the method
~ do....end is the block
~ [2,3,4] is the return object
So the block is a kind of argument passed into the method. This chunk of code will add to the individual element in the array by 1.
[1,2,3].map(&block)
You are passing in the block as an argument.
What map does is take each element in the array, run it through the block .
It is like the array#include? function, which take each element in the array, then compare it against the argument
[1,2,3].include?(2) then return true. In this case, the argument is just a single number.
But in our case, the argument is a whole chunk of code.
the Map function is to pass in each element into the chunk of code, then make the return value of each block into a new array. Then, return the new array.
Comments
Post a Comment