ruby - 这两个 Ruby 枚举器 : [1, 2,3].map 与 [1,2,3].group_by 之间的区别

标签 ruby enumerable enumerator

在 Ruby 中,这两个枚举器在功能上有区别吗?

irb> enum_map = [1,2,3].map
=> #<Enumerator: [1, 2, 3]:map> # ends with "map>"

irb> enum_group_by = [1,2,3].group_by
=> #<Enumerator: [1, 2, 3]:group_by> # ends with "group_by>"

irb> enum_map.methods == enum_group_by.methods
=> true # they have the same methods

什么可以#<Enumerator: [1, 2, 3]:map>这样做<Enumerator: [1, 2, 3]:group_by>不能做,反之亦然?

谢谢!

最佳答案

来自 group_by 的文档:

Groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block and the values are arrays of elements in the collection that correspond to the key.

If no block is given an enumerator is returned.

(1..6).group_by { |i| i%3 }   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}

来自 map 的文档:

Returns a new array with the results of running block once for every element in enum.

If no block is given, an enumerator is returned instead.

(1..4).map { |i| i*i }      #=> [1, 4, 9, 16]
(1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]

如您所见,每个人都做不同的事情,服务于不同的目的。得出结论说两个 API 是相同的,因为它们公开了相同的接口(interface),这似乎错过了面向对象编程的全部目的 - 不同的服务应该公开相同的接口(interface)以启用 polymorphism .

关于ruby - 这两个 Ruby 枚举器 : [1, 2,3].map 与 [1,2,3].group_by 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23842056/

相关文章:

ruby-on-rails - Rails 迁移引用的命名约定

ruby - 为什么 ruby​​ 允许子类访问父类的私有(private)方法?

python - 使用 Ruby popen3 运行 Python 脚本而不显示终端

ruby - 如何在 ruby​​ 中将 with_index 和 with_object 链接到可枚举对象上?

typescript - 如何为属性创建 TypeScript @enumerable(false) 装饰器

ruby - 什么时候枚举器有用?

Ruby:BigDecimal:同时是一个类和一个方法?

c# - 如何处理多个 Enumerable.Zip 调用?

c++ - 有没有办法在枚举条目中存储多个值?

ruby - 如何简化此 Enumerator 代码?