阵列#每个主场迎战阵列#地图 [英] Array#each vs. Array#map
问题描述
hash = { "d" => [11, 22], "f" => [33, 44, 55] }
# case 1
hash.map {|k,vs| vs.map {|v| "#{k}:#{v}"}}.join(",")
=> "d:11,d:22,f:33,f:44,f:55"
# case 2
hash.map {|k,vs| vs.each {|v| "#{k}:#{v}"}}.join(",")
=> "11,22,33,44,55"
唯一的区别是1的情况下使用 vs.map
2的情况下使用 vs.each
。
在这里发生了什么?
推荐答案
阵列#每个
执行用于数组中的每个元素的给定块,然后返回数组本身。
Array#each
executes the given block for each element of the array, then returns the array itself.
阵列#地图
也执行了数组的每个元素的给定块,但返回一个新的数组,其值是块的每个迭代的返回值。
Array#map
also executes the given block for each element of the array, but returns a new array whose values are the return values of each iteration of the block.
例如:假设你有一个数组定义正是如此:
Example: assume you have an array defined thusly:
arr = ["tokyo", "london", "rio"]
然后尝试执行每个
:
arr.each { |element| element.capitalize }
# => ["tokyo", "london", "rio"]
请注意返回的值就是同一阵列。里面的code中的每个
块被执行,但不返回的计算值;而作为code有没有副作用,这个例子不执行有用的工作。
Note the return value is simply the same array. The code inside the each
block gets executed, but the calculated values are not returned; and as the code has no side effects, this example performs no useful work.
在此相反,调用数组的地图
方法返回一个新的数组,其元素是每一轮执行地图中的返回值
块:
In contrast, calling the array's map
method returns a new array whose elements are the return values of each round of executing the map
block:
arr.map { |element| element.capitalize }
# => ["Tokyo", "London", "Rio"]
这篇关于阵列#每个主场迎战阵列#地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!