Array#each vs. Array#map [英] Array#each vs. Array#map

查看:41
本文介绍了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.

only difference is case 1 uses vs.map, case 2 uses vs.each.

这里发生了什么?

推荐答案

Array#each 为数组的每个元素执行给定的块,然后返回数组本身.

Array#each executes the given block for each element of the array, then returns the array itself.

Array#map 也为数组的每个元素执行给定的块,但返回一个新数组,其值是块每次迭代的返回值.

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"]

然后尝试执行each:

arr.each { |element| element.capitalize }
# => ["tokyo", "london", "rio"]

注意返回值只是同一个数组.each 块内的代码被执行,但不返回计算值;并且由于代码没有副作用,这个例子没有执行任何有用的工作.

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.

相反,调用数组的map方法会返回一个新的数组,其元素是每轮执行map块的返回值:

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"]

这篇关于Array#each vs. Array#map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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