This blog is part of our Ruby 2.4 series.
It is a common use case to calculate sum of the elements of an array or values from a hash.
Active Support already implements Enumerable#sum
Until Ruby 2.3,
we had to use Active Support
Enumerable#sum method or we could use
#inject which is used by Active Support under the hood.
Let’s take a look at how
fares on some of the enumerable objects
in Ruby 2.4.
As we can see,
the behavior of
Enumerable#sum from Ruby 2.4 is same
as that of Active Support in case of numbers but not the same
in case of string or array concatenation.
Let’s see what is the difference and how we can make it work
in Ruby 2.4 as well.
Understanding addition/concatenation identity
takes an optional argument
which acts as an accumulator. Both Active Support
and Ruby 2.4 accept this argument.
When identity argument is not passed,
0 is used as default accumulator in Ruby 2.4 whereas
Active Support uses
nil as default accumulator.
Hence in the cases of string and array concatenation,
the error occurred in Ruby because the code attempts to
add a string and array respectively
To overcome this,
we need to pass proper addition/concatenation identity
as an argument to the
The addition/concatenation identity of an object
can be defined as the value with which calling
on an object returns the same object.
What about Rails ?
As we have seen earlier,
Ruby 2.4 implements
favouring numeric operations whereas
also supporting non-numeric callers
with the identity element.
This behavior is not entirely same
as that of Active Support.
But still Active Support can make use
of the native sum method whenever
There is already a
open which uses
Enumerable#sum from Ruby
This will help gain some performance boost
as the Ruby’s method is implemented
natively in C
whereas that in Active Support is
implemented in Ruby.