不能全部或大多数情况下的“每个”被替换为“地图”? [英] Can't all or most cases of `each` be replaced with `map`?

查看:118
本文介绍了不能全部或大多数情况下的“每个”被替换为“地图”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Enumerable#each Enumerable#map 之间的区别是它是返回接收者还是映射结果。回到接收者是微不足道的,你通常不需要在每个之后继续一个方法链,像每个{...} another_method (我可能还没有看到这种情况,即使你想回到接收方,你可以用点击来实现。所以我认为使用 Enumerable#each 的所有或大多数情况可以由 Enumerable#map 替换。我错了吗?如果我是对的,每个的目的是什么? 地图每个

The difference between Enumerable#each and Enumerable#map is whether it returns the receiver or the mapped result. Getting back to the receiver is trivial and you usually do not need to continue a method chain after each like each{...}.another_method (I probably have not seen such case. Even if you want to get back to the receiver, you can do that with tap). So I think all or most cases where Enumerable#each is used can be replaced by Enumerable#map. Am I wrong? If I am right, what is the purpose of each? Is map slower than each?

编辑
当您对返回值不感兴趣时​​,我知道使用每个的常见做法。我对这种做法是否存在感兴趣,但对于这种做法是否符合惯例的观点,我感兴趣。

Edit: I know that there is a common practice to use each when you are not interested in the return value. I am not interested in whether such practice exists, but am interested in whether such practice makes sense other than from the point of view of convention.

推荐答案

map 每个之间的选择应由所需的最终结果决定:新数组或否新数组。 map 的结果可能是巨大的和/或愚蠢的:

The choice between map or each should be decided by the desired end result: a new array or no new array. The result of map can be huge and/or silly:

p ("aaaa".."zzzz").map{|word| puts word} #huge and useless array of nil's

这篇关于不能全部或大多数情况下的“每个”被替换为“地图”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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