阵列#每个主场迎战阵列#地图 [英] Array#each vs. Array#map

查看:182
本文介绍了阵列#每个主场迎战阵列#地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆