Is inject the same thing as reduce in ruby?
More recent versions of the documentation of Enumerable#reduce
specify it explicitly:
The
inject
andreduce
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:
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.