How to get the size of a cloned lazy enumerator

We have an Enumerator :: Lazy object

a = [1,2,3].lazy.map {} #=> <Enumerator::Lazy: #<Enumerator::Lazy: [1, 2, 3]>:map> a.size #=> 3 a.clone.size #=> nil 

Does anyone have a proper explanation for this behavior? I know that size returns the size of the enumerator, or nil if it cannot be calculated lazily. When we clone an object, it returns

 a.clone #=> <Enumerator::Lazy:<Enumerator::Generator:0x00007fdaa80218d8>:each> 
+5
source share
1 answer

I know that size returns the size of the enumerator, or nil if it cannot be calculated lazily.

size for a Enumerator not necessarily the real thing (or at least not as you might think), which may be the reason this change has been implemented.

for instance

 [1,2,3].to_enum.size #=> nil [1,2,3].to_enum(:each) { 1 }.size #=> 1 #=> 1 

or better yet

 [1,2,3].to_enum(:each) { "A" }.size #=> "A" 

When we clone an object, it returns a.clone #=> <Enumerator::Lazy<Enumerator::Generator:0x00007fdaa80218d8>:each>

This seems to be a change in 2.4, when it seems like it goes back to the following: each method (possibly through enum_for ), because in 2.3 the map reference is saved as a size. Obviously, iteration did not occur due to the reversal, and the size cannot be determined in a "lazy" way and therefore nil

+3
source

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


All Articles