问题
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);
回答1:
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.
来源:https://stackoverflow.com/questions/41636558/why-is-rangesum-defined-in-enumerable-module