Is inject the same thing as reduce in ruby?
RubyAliasReduceInjectRuby Problem Overview
I saw that they were documented together here. Are they the same thing? Why does Ruby have so many aliases (such as map/collect for arrays)? Thanks a lot.
Ruby Solutions
Solution 1 - Ruby
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!
Solution 2 - Ruby
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.
Solution 3 - Ruby
> 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:
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.