Why is Range#sum defined in Enumerable module?

半世苍凉 提交于 2020-01-03 12:31:14

问题


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 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.



来源:https://stackoverflow.com/questions/41636558/why-is-rangesum-defined-in-enumerable-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!