Array#each vs. Array#map [英] 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屋!