Re:Ruby vs. Python comes down to the for loop
by halostatue on Friday November 12, 2021 @02:03PM
(#29203239)
#collect is an alias for #reduce, not #map, making it like Python reduce().
Re:Ruby vs. Python comes down to the for loop
by dragonwriter on Friday November 12, 2021 @02:12PM
(#29203360)
> #collect is an alias for #reduce
It’s not, though. (If it was, we could write about its equivalence with Python’s [from functools in py3, core in Py2] reduce function, though, saying much the same thing as about the actual equivalence with map upthread, except reduce/inject is less often a substitute for generators than map/collect.)
#map is an alias for #collect. [0]
#reduce has the alias #inject. [1]
[0] https://ruby-doc.org/core-3.0.2/Enumerable.html#method-i-col...
[1] https://ruby-doc.org/core-3.0.2/Enumerable.html#method-i-inj...
Re:Ruby vs. Python comes down to the for loop
by pansa2 on Friday November 12, 2021 @05:42PM
(#29205369)
Then should the example in the above comment, `some_enum.collect(&:+)`, be using reduce instead of collect?
Re:Ruby vs. Python comes down to the for loop
by busterarm on Friday November 12, 2021 @08:04PM
(#29206360)
Yes. My bad. :)
I haven't been a professional Rubyist in some years but my habit here was to use inject.
Re:Ruby vs. Python comes down to the for loop
by halostatue on Friday November 12, 2021 @08:10PM
(#29206393)
You’re right. My apologies.
(Enumerable#lazy gives you an object where collect/map is, and other merhods are, lazy rather than eager.)
> I feel like it takes the role that generators have in Python
Ruby has generators, though in either Ruby or Python map/collect (the lazy versions, in Ruby) can be used for some of their uses, since it basically produces a generator from an input collection or generator and a mapping function.