array.each和array.map有何不同? [英] How are array.each and array.map different?

查看:126
本文介绍了array.each和array.map有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Array#each vs. Array #map





ruby-1.9.2-p180 :006 > ary = ["a", "b"]
 => ["a", "b"] 
ruby-1.9.2-p180 :007 > ary.map { |val| p val }
"a"
"b"
 => ["a", "b"] 
ruby-1.9.2-p180 :008 > ary.each { |val| p val }
"a"
"b"
 => ["a", "b"] 

ruby-1.9.2-p180 :009 > ary.map { |val| val << "2" }
 => ["a2", "b2"] 
ruby-1.9.2-p180 :010 > ary.each { |val| val << "2" }
 => ["a22", "b22"] 


推荐答案

< a href =http://en.wikipedia.org/wiki/Side_effect_%28computer_science%29 =noreferrer>副作用是相同的,这给你的逆向工程增加了一些困惑。

The side effects are the same which is adding some confusion to your reverse engineering.

是的,都在遍历数组(实际上,任何混合 Enumerable )但 map 将返回由块结果组成的数组,而每个将返回原始数据阵列。 每个的返回值很少在Ruby代码中使用,但 map 最重要的功能工具

Yes, both iterate over the array (actually, anything that mixes in Enumerable) but map will return an Array composed of the block results while each will just return the original Array. The return value of each is rarely used in Ruby code but map is one of the most important functional tools.

BTW,您可能很难找到文档,因为 map Enumerable 中的方法,而每个 Enumerable 模块所需的一种方法)是 Array 中的方法>。

BTW, you may be having a hard time finding the documentation because map is a method in Enumerable while each (the one method required by the Enumerable module) is a method in Array.

作为一个琐事说明:地图实施基于每个

As a trivia note: the map implementation is based on each.

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

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