ruby - Ruby 中 map 和 collect 的区别?

标签 ruby arrays map collect

我用 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/

相关文章:

ruby - 我应该如何使用 Datamapper 保护 Sinatra 应用程序中的批量分配?

c# - 如何从 C# 中的两个数组中获取两个随机字符串

javascript - 在javascript中查找嵌套对象数组中的百分比值

ios5 - MKPointAnnotation : title always visible. 可能吗?

c++ - 我如何找出 std::map 方法可以抛出哪些异常?

c++ - 等效于 std::map 的 remove_if

ruby - 测试 thor CLI 时禁用警告

ruby-on-rails - 使用 Rails : syck has been removed, psych

ruby-on-rails - 将集合和自定义字段添加到选择框

c++ - 结构成员数组的深拷贝