gpt4 book ai didi

ruby - Ruby 中 map 和 collect 的区别?

转载 作者:数据小太阳 更新时间:2023-10-29 06:16:11 25 4
gpt4 key购买 nike

我用 Google 搜索了这个并得到了零散/矛盾的意见 - 在 Ruby/Rails 中对数组执行 map 和执行 collect 之间实际上有什么区别吗?

docs似乎没有任何建议,但在方法或性能上可能存在差异吗?

最佳答案

没有区别,事实上 map 在 C 中作为 rb_ary_collectenum_collect 实现(例如, map 在数组和任何其他枚举上,但 mapcollect 之间没有区别。


为什么 mapcollect 都存在于 Ruby 中? map 函数在不同的语言中有许多命名约定语言。 Wikipedia provides an overview :

The map function originated in functional programming languages but is today supported (or may be defined) in many procedural, object oriented, and multi-paradigm languages as well: In C++'s Standard Template Library, it is called transform, in C# (3.0)'s LINQ library, it is provided as an extension method called Select. Map is also a frequently used operation in high level languages such as Perl, Python and Ruby; the operation is called map in all three of these languages. A collect alias for map is also provided in Ruby (from Smalltalk) [emphasis mine]. Common Lisp provides a family of map-like functions; the one corresponding to the behavior described here is called mapcar (-car indicating access using the CAR operation).

Ruby 为来自 Smalltalk 世界的程序员提供了一个别名,让他们感觉更自在。


为什么数组和枚举有不同的实现方式?枚举是一种通用的迭代结构,这意味着 Ruby 无法预测下一个元素是什么(您可以定义无限枚举,参见 Prime 示例)。因此它必须调用一个函数来获取每个连续的元素(通常这将是 each 方法)。

数组是最常见的集合,因此优化其性能是合理的。由于 Ruby 非常了解数组的工作原理,因此它不必调用 each 而只能使用简单的 pointer manipulation。这明显更快。

许多 Array 方法存在类似的优化,例如 zipcount

关于ruby - Ruby 中 map 和 collect 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5254732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com