Why is the sum of Range # defined in the Enumerable module?

In Ruby 2.4 and for entire ranges Range(Enumerable)#sum optimized to return the result directly, without repeating all the elements.

I do not understand why the corresponding code is defined in enum.c for Enumerable , and not range.c for the Range class.

Why does Enumerable know about classes that include it (e.g. Range , Hash , ...) and check their type instead of letting these classes overwrite Enumerable#sum ?

In the enum.c field:

  return int_range_sum(beg, end, excl, memo.v); # or hash_sum(obj, &memo); 
+6
source share
1 answer

Because rb_range_values can be true for arbitrary instances of the class (not just explicit Range s), and we all want them for optimization too.

This basically means that as soon as the instance responds with begin and end (and exclude_end? Btw,), we need to introduce this optimization.

+6
source

Source: https://habr.com/ru/post/1014060/


All Articles