在 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/