Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Something that I only realised the other day which made me feel kinda embarrassed: in ruby, the reduce method is called inject.

For years I've been doing MapReduce functions, without realising it. MapReduce was in my mental pile of "genius things that cleverer people than me do, must be looked into when there is time."

For info on inject: http://blog.jayfields.com/2008/03/ruby-inject.html



In Ruby the reduce method is also called reduce:

    [1,2,3].inject{|s,i| s += i}
    => 6
    [1,2,3].reduce{|s,i| s += i}
    => 6


Reduce is an alias for inject, and depending on which template you use to generate the docs, method aliases are not given the same prominence as full methods. Some templates simply say "this method is also known as..." underneath the original method in a tiny font.

If it were the other way around, and inject was an alias for reduce, I think there would be a lot less confused rubyists.


I've wrote about these ancient ways of great languages a while ago: http://metaphysicaldeveloper.wordpress.com/2009/05/02/closur...


What would it do on an empty list? It should probably take an argument for the empty case...

What is the history behind the name "inject" here?


The name comes from Smalltalk. I imagine that the idea is that you're "injecting" an operator between items in the list: 1 2 3 4 becomes 1 + 2 + 3 + 4.


By default, inject uses the first element of the array as the argument, so it would use nil on an empty list. It optionally takes an argument to kick off the process.


Most likely Ruby takes the name inject from Smalltalk. (Smalltalk also uses 'collect' for map, 'select' for filter, 'reject' for an inverse filter.)


Thank you for pointing out the history! The names inject, collect, select, and reject drive me crazy for some reason. Maybe it's because they rhyme. But every time I saw them, I wondered why Matz made these up instead of using map/filter/reduce. At least now I know.


A nice relevant post from raganwald - http://weblog.raganwald.com/2008/02/1100inject.html


Thanks you for your nice words. I would have suggested this one, although it has been discussed Ad Nauseum on HN in the past:

http://weblog.raganwald.com/2007/03/why-why-functional-progr...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: