In Ruby 2.4 and for Integer Ranges, Range(Enumerable)#sum
is optimized to return a result directly, without iterating over all elements.
I don't understand why the corresponding code is defined in enum.c
for the Enumerable
module and not in range.c
for Range
class.
Why should Enumerable
know about classes that include it (e.g. Range
, Hash
, ...) and check for their type instead of letting those classes overwrite Enumerable#sum
?
Seen in enum.c
:
return int_range_sum(beg, end, excl, memo.v);
# or
hash_sum(obj, &memo);
Because rb_range_values
might be true
for arbitrary class instances (not only explicit Range
s) and we all want them to be optimized too.
Basically, it means that as soon as an instance responds to both begin
and end
(and exclude_end?
btw,) we are to enter this optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With