地图、每个和收集之间有什么区别?

发布于 2025-01-08 19:27:32 字数 84 浏览 3 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岛徒 2025-01-15 19:27:32

eachmapcollect 不同,但 mapcollect 是相同的(从技术上讲,mapcollect 的别名,但根据我的经验,map 使用得更频繁)。

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

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

mapcollect 生成一个新的 < code>Array 包含应用于接收器每个元素的块的结果:

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

还有 map! / collect!Arrays;他们就地修改接收器:

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]"

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 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 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]

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]"
北陌 2025-01-15 19:27:32

Each 将评估该块,但丢弃 Each 块的评估结果并返回原始数组。

irb(main):> [1,2,3].each {|x| x*2}
=> [1, 2, 3]

Map/collect 返回一个数组,该数组是为数组中的每个项目调用块的结果而构造的。

irb(main):> [1,2,3].collect {|x| x*2}
=> [2, 4, 6]

Each will evaluate the block but throws away the result of Each block's evaluation and returns the original array.

irb(main):> [1,2,3].each {|x| x*2}
=> [1, 2, 3]

Map/collect return an array constructed as the result of calling the block for each item in the array.

irb(main):> [1,2,3].collect {|x| x*2}
=> [2, 4, 6]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文