更新时间:2023-08-19 19:02:22
阵列#每个
执行用于数组中的每个元素的给定块,然后返回数组本身。
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"]