地图、每个和收集之间有什么区别?
在 Ruby 中,each
、map
和 collect
的功能有什么区别吗?
In Ruby, is there any difference between the functionalities of each
, map
, and collect
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
each
与map
和collect
不同,但map
和collect
是相同的(从技术上讲,map
是collect
的别名,但根据我的经验,map
使用得更频繁)。each
为 (Enumerable
) 接收器中的每个元素执行封闭块:map
和collect
生成一个新的 < code>Array 包含应用于接收器每个元素的块的结果:还有
map!
/collect!
在Arrays;他们就地修改接收器:
each
is different frommap
andcollect
, butmap
andcollect
are the same (technicallymap
is an alias forcollect
, but in my experiencemap
is used a lot more frequently).each
performs the enclosed block for each element in the (Enumerable
) receiver:map
andcollect
produce a newArray
containing the results of the block applied to each element of the receiver:There's also
map!
/collect!
defined onArray
s; they modify the receiver in place:Each
将评估该块,但丢弃Each
块的评估结果并返回原始数组。Map
/collect
返回一个数组,该数组是为数组中的每个项目调用块的结果而构造的。Each
will evaluate the block but throws away the result ofEach
block's evaluation and returns the original array.Map
/collect
return an array constructed as the result of calling the block for each item in the array.