Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Range#sum defined in Enumerable module?

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);
like image 516
Eric Duminil Avatar asked Jan 13 '17 14:01

Eric Duminil


1 Answers

Because rb_range_values might be true for arbitrary class instances (not only explicit Ranges) 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.

like image 78
Aleksei Matiushkin Avatar answered Nov 15 '22 11:11

Aleksei Matiushkin