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.
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!
inject
so that users don't have to read the two description and try to figure out if they are the same... doesn't this go with the DRY principle? –
Recording 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.
&:+
), reduce, if it's a block, inject –
Aeroembolism 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.
© 2022 - 2024 — McMap. All rights reserved.