map、each 和 collect 之间有什么区别? [英] What is the difference between map, each, and collect?

查看:72
本文介绍了map、each 和 collect 之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,eachmapcollect 的功能有什么区别吗?

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

推荐答案

eachmapcollect不同,但mapcollect 是相同的(技术上mapcollect 的别名,但根据我的经验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

mapcollect 生成一个新的 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 之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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