4 ms·
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
by SandB0x 16y ago
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
- JonnieCache 16y agoReduce 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.
- DanielRibeiro 16y agoI've wrote about these ancient ways of great languages a while ago: http://metaphysicaldeveloper.wordpress.com/2009/05/02/closures-collections-and-some-functional-programming/ http://metaphysicaldeveloper.wordpress.com/2009/05/02/closur...
- Peaker 16y agoWhat 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?
- kejadlen 16y agoBy 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.
- kragen 16y agoThe 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.