[ACCEPTED]-Is inject the same thing as reduce in ruby?-inject

Accepted answer
Score: 167

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

Score: 9

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

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

Score: 3

Are they the same thing?

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

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

It boils down to the language's 13 approach

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

enter image description here

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

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

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

More Related questions