为什么在Enumerable模块中定义了Range#sum?

[英]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.

在Ruby 2.4和Integer Ranges中,Range(Enumerable)#sum被优化为直接返回结果,而不迭代所有元素。

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.

我不明白为什么在enum.c中为Enumerable模块定义了相应的代码,而在Range.c中没有在range.c中定义。

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?

为什么Enumerable应该知道包含它的类(例如Range,Hash,...)并检查它们的类型而不是让这些类覆盖Enumerable#sum?

Seen in enum.c :

见于enum.c:

 return int_range_sum(beg, end, excl, memo.v);
 # or
 hash_sum(obj, &memo);

1 个解决方案

#1


6  

Because rb_range_values might be true for arbitrary class instances (not only explicit Ranges) and we all want them to be optimized too.

因为对于任意类实例(不仅是显式范围),rb_range_values可能都是真的,我们都希望它们也被优化。

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.

基本上,这意味着只要实例响应开始和结束(以及exclude_end?btw,),我们就会进入此优化。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2017/01/13/bdeb4e8beb0b4cf684064019f26e5e81.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号