Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is inject the same thing as reduce in ruby?

People also ask

What is inject in Ruby?

Inject applies the block result + element. to each item in the array. For the next item ("element"), the value returned from the block is "result". The way you've called it (with a parameter), "result" starts with the value of that parameter. So the effect is adding the elements up.

What is reduce in Ruby?

Reduce, or inject, is a useful method in any programming language but we 'll focus on ruby for now. Reduce is an enumerable method that can be used on hashes or arrays to reduce them into a single value or object. Say you wanted to get the sum of an array without the reduce method.

How do you sum in Ruby?

Ruby | Enumerable sum() functionThe sum() of enumerable is an inbuilt method in Ruby returns the sum of all the elements in the enumerable. If a block is given, the block is applied to the enumerable, then the sum is computed. If the enumerable is empty, it returns init. Parameters: The function accepts a block.


Yes, and it's also called fold in many other programming languages and in Mathematics. Ruby aliases a lot in order to be intuitive to programmers with different backgrounds. If you want to use #length on an Array, you can. If you want to use #size, that's fine too!


More recent versions of the documentation of Enumerable#reduce specify it explicitly:

The inject and reduce methods are aliases. There is no performance benefit to either.


Are they the same thing?

Yes, aliases run the exact same code in the end.

Why does Ruby have so many aliases (such as map/collect for arrays)?

It boils down to the language's approach

Different languages have different approaches, I tried to visualize it here:

enter image description here

Ruby does it in favor of developer productivity. Basically, by having aliases you give programmers from different programming languages and human languages backgrounds to write code more intuitively.

However, they can also help your code's clarity because some things may have different semantic possibilities like the method midnight() can also be expressed as start_of_day or end_of_day. Those can be more clear depending on the context.

By the way, some programmers use inject and reduce to differentiate between different semantic situations too.