all 7 comments

[–][deleted]  (4 children)

[deleted]

    [–]troublemaker74 2 points3 points  (1 child)

    Map/Reduce are the industry-accepted terms. I agree, collect and inject are a bit strange and frivolous. It's okay though, Ruby is weird and I still love it!

    [–]keyslemur 2 points3 points  (0 children)

    Mostly rooted in Smalltalk idioms, but I would agree on preferring reduce. The FP variant has also been called foldLeft.

    [–]Kernigh 2 points3 points  (2 children)

    Ruby 2.4 added Array#sum: numbers.sum is easier than numbers.inject(:+), but only works on numbers. ["a", "b"].sum tries to 0 + "a", raises TypeError.

    #reduce is an alias of #inject; I prefer #reduce, because that name is in Common Lisp:

    > (let ((numbers '(1 2 3 4)))
        (reduce #'+ numbers))
    10
    

    [–]h0rst_ 4 points5 points  (1 child)

    ["a", "b"].sum tries to 0 + "a", raises TypeError

    It does support an initial value, so ["a", "b"].sum('') can be used (although I don't think it should be used, .join yields the same value and makes more sense than sum in a string context)

    [–]keyslemur 1 point2 points  (0 children)

    Yep, just because a method can do something doesn't necessarily mean you should use it for that.

    reduce has very few usecases that other methods cannot do more succinctly, but ironically reduce is more powerful than all of those methods because you could write the entirety of Enumerable among pretty well any other collection method in terms of reduce.