map、each 和 collect 之间有什么区别?

编程入门 行业动态 更新时间:2024-10-20 05:33:23
本文介绍了map、each 和 collect 之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 Ruby 中,each、map 和 collect 的功能有什么区别吗?

In Ruby, is there any difference between the functionalities of each, map, and collect?

推荐答案

each与map和collect不同,但map 和 collect 是相同的(技术上map 是collect 的别名,但根据我的经验mapcode> 的使用频率更高).

each is different from map and collect, but map and collect are the same (technically map is an alias for collect, but in my experience map is used a lot more frequently).

each 为 (Enumerable) 接收器中的每个元素执行封闭块:

each performs the enclosed block for each element in the (Enumerable) receiver:

[1,2,3,4].each {|n| puts n*2} # Outputs: # 2 # 4 # 6 # 8

map 和 collect 生成一个新的 Array 包含应用于接收器的每个元素的块的结果:

map and collect produce a new Array containing the results of the block applied to each element of the receiver:

[1,2,3,4].map {|n| n*2} # => [2,4,6,8]

还有 map!/collect! 定义在 Array 上;他们就地修改接收器:

There's also map! / collect! defined on Arrays; they modify the receiver in place:

a = [1,2,3,4] a.map {|n| n*2} # => [2,4,6,8] puts a.inspect # prints: "[1,2,3,4]" a.map! {|n| n+1} puts a.inspect # prints: "[2,3,4,5]"

更多推荐

map、each 和 collect 之间有什么区别?

本文发布于:2023-11-26 00:24:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631924.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   map   collect

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!